处理请求超时问题(session)

在java中:

public class LoginFilter implements Filter {
    private String sessionKey = "userid";
    public void init(FilterConfig filterConfig) throws ServletException {
        String key = filterConfig.getInitParameter("sessionKey");
        sessionKey = key == null ? sessionKey : key;
	}
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
                HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
                HttpSession session = req.getSession();
                req.setCharacterEncoding("utf-8");
                rep.setContentType("text/html;charset=utf-8");String currentURL = req.getRequestURI();
String contextPath = req.getContextPath();
		if (null == session || null == session.getAttribute(sessionKey)
				|| "".equals((String) session.getAttribute(sessionKey))) {
			// 如果判断是 AJAX 请求,直接设置为session超时
			if (req.getHeader("x-requested-with") != null
					&& req.getHeader("x-requested-with").equals("XMLHttpRequest")) {
				System.out.println("用户已失效");
				rep.setHeader("sessionstatus", "timeout");
			} else {
				rep.sendRedirect(contextPath);
			}
		} else {
			filterChain.doFilter(request, response);
		}
	}
	public void destroy() {
	}
}

在js中:
 $.ajaxSetup({ 
             contentType:"application/x-www-form-urlencoded;charset=utf-8", 
             complete:function(XMLHttpRequest,textStatus){ 
                     var sessionstatus=XMLHttpRequest.getResponseHeader("sessionstatus"); //通过XMLHttpRequest取得响应头,sessionstatus,
                     if(sessionstatus=="timeout"){  //如果超时就处理 ,指定要跳转的页面

                                         window.location.replace("${path}/common/login.do"); 

                                 } 

                      } 

             } 

      });

在web.xml中:


		LoginFilter
		com.wonders.common.filter.LoginFilter
	

	
		LoginFilter
		*.do
	

你可能感兴趣的:(处理请求超时问题(session))