如何使用拦截器Spring mvc在会话过期后重定向

时间:2015-12-29 06:18:54

标签: java spring-mvc

            *@Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                        throws Exception {

                    System.out.println("INTERCEPTING---");
                    if(request !=null && request.getParameter("email")!=null){

                        System.out.println("session is NOT null------");
                        session = request.getSession();
                        session.setAttribute("user", request.getParameter("email"));

                    }else{

                        try{

                            if (session==null){

                                System.out.println("session lost");

                            }

                        }catch(IllegalStateException exception){

                            System.out.println("session expired");
                            "redirect:http://localhost:8080/web/authservice/fail";

/ 这是我使用的重定向,我也尝试了模型和视图,但它不起作用 /                             }

                    }

                    return true;
                }
    /*in the above method how should I redirect. Its not redirecting...............
Im unable to redirect the after the session expired it gives me a response commit exception. I ve been trying for hours no solution

请提供合适的解决方案* /

1 个答案:

答案 0 :(得分:0)

改为使用servlet过滤器(根据web.xml中的intercepet要求放置它)。

public class CustomRequestFilter implements Filter {
      WebApplicationContext springContext;
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
        springContext = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException, LicenseException {
        HttpServletRequest request = (HttpServletRequest) req;

        if (XXX) {
            //forward or redirect as per requirement
                request.getRequestDispatcher("/WEB-INF/jsp/errors/SystemError.jsp").forward(request, response);
        }
        chain.doFilter(request, response);
    }

}