doFilter with HttpServletRequest

时间:2017-08-23 02:00:45

标签: java spring-mvc servlets

我坚持使用HttpServletRequest的doFilter。

我正在尝试替换该请求的新网址。

我的代码如下:

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
    throws IOException, ServletException {

     HttpServletRequest httpReq = (HttpServletRequest) req;
     HttpServletResponse httpRes = (HttpServletResponse) res;

     //If request resources ==> Continue
     if(httpReq.getContextPath().startsWith(httpReq.getContextPath()+"/resources")){
         chain.doFilter(req, res);
         return;
     }
     HttpSession session = httpReq.getSession();
     EmployeeDTO currentEmployee =(EmployeeDTO)session.getAttribute("currentEmployee");
    //If dont have session ==> Return login page
     if(currentEmployee == null){
        String requestURI = "";
         requestURI = httpReq.getRequestURI().replace(httpReq.getRequestURI(), httpReq.getContextPath()+ "/login");
         System.out.println(requestURI);
         //httpRes.reset();
         //httpRes.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
         //httpRes.setHeader("Location", requestURI);
         httpRes.sendRedirect(requestURI);
         chain.doFilter(req, res);
        return;
     }
     chain.doFilter(req, res);
     return;
}

但上面的代码仍无效。我该怎么做?

提前致谢!

1 个答案:

答案 0 :(得分:0)

为什么在设置重定向响应后必须执行chain.doFilter()?

private FilterConfig filterConfig;

public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
    throws IOException, ServletException {

     HttpServletRequest httpReq = (HttpServletRequest) req;
     HttpServletResponse httpRes = (HttpServletResponse) res;
         HttpSession session = httpReq.getSession();
         boolean requestResources = false;

     //If request resources ==> Continue
     if(httpReq.getContextPath().startsWith(httpReq.getContextPath()+"/resources")){
        requestResources =  true;
     }     
     if(session != null){
            EmployeeDTO currentEmployee =(EmployeeDTO)session.getAttribute("currentEmployee");
     }
     if(requestResources || currentEmployee != null){
            chain.doFilter();
     }else if(currentEmployee == null){         
         String loginURI = //hardcode the loginURI here. 
         httpRes.sendRedirect(loginURI);
         /*alternatively use the following to do an internal forward rather than a redirect      
         RequestDispatcher rd = filterConfig.getServletContext().getRequestDispatcher(loginURI); //here the loginURI path should not have the context in the url.
                rd.forward(servletReq, response);
         */
     }     

}

我还重构了你的代码以删除冗余和多个'return'语句