ajax session失效后,跳转到登录页面的全局处理

来源:互联网 发布:深圳知豆电动汽车租赁 编辑:程序博客网 时间:2024/05/17 09:06

在SaaS系统中, 我们需要考虑, 用户停留页面时间过长导致session失效后, ajax方法无法正确运行, 我们又不希望在每个ajax方法中, 来判断是否登录, 未登录的情况下就跳转到登录页.


我们的解决方案是:

首先,有一个Intercepter 实现了HandlerInterceptor接口.

在preHandler方法中, 判断handler对象类型, 我们只处理 spring controller方法.

if (handler instanceof HandlerMethod) {            // intercept            Account account = (Account) session.getAttribute("account");            if (account == null) {                HandlerMethod handlerMethod = (HandlerMethod) handler;                // 根据请求的是否是ajax方法, 来判断是直接302还是返回一个JSON                if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) { // ajax方法                    PrintWriter printWriter = response.getWriter();                    response.setStatus(499);                    String url = request.getHeader("referer");                    if (org.springframework.util.StringUtils.isEmpty(url)) {                        url = loginPath;                    }                    printWriter.print(url);                } else {                    String redirectUrl = loginPath;                    session.setAttribute("retUrl",  request.getRequestURL().toString());                    response.sendRedirect(redirectUrl);                }                return false;            } else {                List<Role> roleList = (List<Role>) session.getAttribute("roles");                SessionHolder.setAccount(account);                SessionHolder.setRoles(roleList);                return true;            }        }


在前端页面加入:

$.ajaxSetup({        statusCode: {            499: function (data) {                window.location.href = data.responseText;            }        }    });



0 0
原创粉丝点击