web項目中使用shiro權限管理,session過時,Ajax請求的處理方式。

// 服務端代碼
@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();
		}
	});

});html

相關文章
相關標籤/搜索