ajax session失效后,跳转到登录页面的全局处理
发布时间:2020-12-16 03:29:51 所属栏目:百科 来源:网络整理
导读:在SaaS系统中,我们需要考虑,用户停留页面时间过长导致session失效后,ajax方法无法正确运行,我们又不希望在每个ajax方法中,来判断是否登录,未登录的情况下就跳转到登录页. 我们的解决方案是: 首先,有一个Intercepter 实现了HandlerInterceptor接口. 在preHand
在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; } } }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |