getServletContext()找不到这个路径

Posted 小鹏_戛然而止

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了getServletContext()找不到这个路径相关的知识,希望对你有一定的参考价值。

我的一开始的源码是:

public class BankInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        
         String username =  (String)request.getSession().getAttribute("adminusername");   
            if(username == null){
               
               response.sendRedirect(request.getServletContext().getContextPath()+"/admin/login");
                return false;  
            }else  
                return true;     
    }

 

下面是报错:

 

 

 

方法一:

getServletContext().getContextPath() 没有这个方法当然报错了。
你可以用request.getContextPath();

 

public class BankInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        
         String username =  (String)request.getSession().getAttribute("adminusername");   
            if(username == null){
               
               response.sendRedirect(request.getServletContext().getContextPath()+"/admin/login");
                return false;  
            }else  
                return true;     
    }

方法二:

在一开始的基础上加上.getSession()

public class BankInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        
         String username =  (String)request.getSession().getAttribute("adminusername");   
            if(username == null){
               
               response.sendRedirect(request.getSession().getServletContext().getContextPath()+"/admin/login");
                return false;  
            }else  
                return true;     
    }

以上是关于getServletContext()找不到这个路径的主要内容,如果未能解决你的问题,请参考以下文章