Ajax请求Session超时的解决办法:拦截器 + 封装jquery的post方法

目标:前端系统,后端系统等,统一处理Session超时和系统错误的问题。

可能需要处理的问题:Session超时、系统500错误、普通的业务错误、权限不足。

同步请求
 
           Session超时,登录拦截器,重定向到登录页面。
           500等系统错误,SpringMVC自定义ExceptionHanlder,跳转到系统错误页面,给访客友好的提示。 
            业务错误和权限不足,与500类似。

            相对而言,同步方式,处理起来还是比较容易的。

异步请求: 

        2种方式

1.后端登录拦截器,发现Session超时,给个标记。
   后端系统错误捕捉,给个标记。

  比如:
  
if (CommonUtil.isAjaxRequest(request)) {
			response.setHeader(BERROR, "yes");  
             CommonUtil.jsonError(response);
             return null;
		} 



  前端
  
<script>
	$(function() {
		 $.ajaxSetup({
			contentType : "application/json;charset=utf-8",
			complete : function(XMLHttpRequest, textStatus) {
				// 通过XMLHttpRequest取得响应头,
				var blogin = XMLHttpRequest.getResponseHeader("blogin");
				if (blogin == "yes") {
					alert("Session time out2");
					window.location = "${frontLoginUrl}";
				}
				var berror = XMLHttpRequest.getResponseHeader("berror");
				if (berror == "yes") {
					alert("Session error2");
				}
			}
		}); 
	});
</script> 



2. 封装jquery的post方法。
  
function post(url, params, fn) {
	$.post(url, params, function(data) {
        if(data.code==-1){
        	alert("Session time out");
        	return;
        }
        if(data.code==-5){
        	alert("System error.");
        	return;
        }
        if(data.code ==0){
        	alert("出了点小问题,"+data.msg);
        	return;
        }
        if(data.code == -2){
        	alert("权限不足,请联系网站管理员.");
        	return;
        }
        fn(data);
	});
}



   调用方式:
  
post(base + "/home/bankcard/doadd.json", {
			"bank" : bank,
			"card" : card
		}, function(data) { 

} 



参考资料
http://daichangfu.iteye.com/blog/1705097、某前端王的建议

补充几点

1.后端拦截器加标记。
   好处是:前端用ajaxSetup,前端没有干扰到任何已有的代码。比如原来$.post不用修改。
   坏处是:后端要改。

2.前端统一封装post,正好反过来。 
   前端需要修改已有的代码。 
   后端不需要修改。 

原文地址:https://www.cnblogs.com/qitian1/p/6462808.html