对Ajax请求做Session过期判断

Posted 学习笔记和总结

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对Ajax请求做Session过期判断相关的知识,希望对你有一定的参考价值。

 

 

 1 // 全局Ajax设置, 用于session过期判断
 2 function ajaxSetup() {
 3     $.ajaxSetup({
 4         timeout : 10000,
 5         beforeSend : function(xhr) {
 6             //添加ajax请求标识
 7             xhr.setRequestHeader("ajaxReq", "ajax");
 8         },
 9         complete : function(xhr, ts) {
10             if (xhr.statusText == ‘sessiontimeout‘ && xhr.status == 403) {
11                 // 跳转
12                 window.location.href = "login.jsp";
13             }
14         }
15     });
16 }

 

 1 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
 2 
 3         HttpServletRequest req = (HttpServletRequest) request;
 4         HttpServletResponse res = (HttpServletResponse) response;
 5         String servletPath = req.getServletPath();
 6         
 7         if(except.contains(req.getRequestURI())){
 8             chain.doFilter(request, response);
 9         }
11         
13         Object sessionObj = req.getSession().getAttribute(key);
14         if(sessionObj==null){
15             //如果是ajax请求
16             if(req.getHeader("ajaxReq")!=null && req.getHeader("ajaxReq").equals("ajax")){
17                 res.setHeader("sessionState", "timeout");
18                 res.setStatus(403);
19                 return;
20             }else{
21                 chain.doFilter(request, response);
22                 String contextPath = req.getContextPath();
23                 String redirect = servletPath + "?" + StringUtils.defaultString(req.getQueryString());
24                 res.sendRedirect(contextPath + forward + "?redirect=" + URLEncoder.encode(redirect, "UTF-8"));
25             }
26             
27         }else{
28             // pass the request along the filter chain
29             chain.doFilter(request, response);
30             System.out.println("chain.do after");
31         }
32         
33     }

 

以上是关于对Ajax请求做Session过期判断的主要内容,如果未能解决你的问题,请参考以下文章

spring框架发送ajax检查session是不是过期

shiro session过期后ajax请求跳转(转)

session过期,拦截ajax请求并跳转登录页面

flask session session已过期,再发送ajax请求如何处理?

session过期时ajax请求刷新浏览器

重写ajax方法实现异步请求session过期时跳转登录页面