// 服务端代码 @RequestMapping(value = { "/login-form.html", "/" }, method = GET) public String loginForm() { if(contextService.isAuthenticated()) { return "redirect:/home.html"; } else { HttpServletRequest request = contextService.getRequest(); HttpServletResponse response = contextService.getResponse(); boolean isAjax = false; Enumeration<String> values = request.getHeaders("X-Requested-With"); while(values.hasMoreElements()) { String value = values.nextElement(); if("XMLHttpRequest".equalsIgnoreCase(value)) { isAjax = true; break; } } if(isAjax) { response.setHeader("Session-Status", "timeout"); response.setHeader("Login-Path", contextService.getContextPath()); } return "/login-form"; } }
// 前端代码 $(function() { $(document).ajaxComplete(function(event, xhr, settings) { if (xhr.getResponseHeader('Session-Status') == 'timeout') { if (xhr.getResponseHeader('Login-Path')) { window.location.replace(xhr.getResponseHeader('Login-Path')); } else { alert("Session timeout, please relogin!"); } } else if(403 == xhr.status) { window.location.reload(); } });
});