ajax请求session失效重定向到登录页面

在ajax请求的页面引入一个自定义的AjaxRedirect.js的文件

AjaxRedirect.js的代码如下:

$(function(){
    $.ajaxSetup({
        type: 'POST',
        complete: function(xhr,status) {
            var sessionStatus = xhr.getResponseHeader('sessionstatus');
            if(sessionStatus == 'timeout') {
                var top = getTopWinow();
                alert('10分钟没有操作, session已过期, 请重新登录.');
                top.location.href = '../LoginController/toLoginPage.do'; //去到登录页面的请求            
            }
        }
    });
    function getTopWinow(){
        var p = window;
        while(p != p.parent){
            p = p.parent;
        }
        return p;
    }
})

过滤器中判断有没有登录的代码如下:

 1 private void checkLogin(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
 2             throws IOException, ServletException {
 3         Account acc = (Account) req.getSession().getAttribute("acc");
 4         if (acc != null) {
 5             chain.doFilter(req, res);
 6             return;
 7         }
 8         // session失效的情况
 9         // 1.判断是ajax请求
10         if (req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equals("XMLHttpRequest")) {
11             res.setHeader("sessionstatus", "timeout");
12         } else {// 2.不是ajax请求
13             res.sendRedirect("../LoginController/toLoginPage.do");
14         }
15     }
原文地址:https://www.cnblogs.com/suhfj-825/p/8116906.html