后台拦截器代码:
// 判断是否是AJAX请求
if (isAjaxRequest(request)) {
log.info("AjaxRequest请求");
ActionContext ac = arg0.getInvocationContext();
HttpServletResponse response = (HttpServletResponse)ac.get(StrutsStatics.HTTP_RESPONSE);
response.setHeader("sessionstatus", "timeout");//返回前台的标志
//response.sendError(518, "session timeout.");//5**,表示服务器错误
return null;
}
/**
* 判断是否是ajax请求
* @param request
* @return
*/
private boolean isAjaxRequest(HttpServletRequest request) {
String header = request.getHeader("X-Requested-With");
if (header != null && "XMLHttpRequest".equals(header)) {
return true;
} else {
return false;
}
}
/**
* =============js代码===================================
* 设置未来(全局)的AJAX请求默认选项
* 主要设置了AJAX请求遇到Session过期的情况
*/
var flag = true;//防止重复点击
var domain = document.domain;
var ip = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
var path = (ip.test(domain))?("http://"+domain+":8081/WSS"):("http://"+document.domain);
console.log(path);
$.ajaxSetup({
type: 'POST',
complete: function(xhr,status) {
var sessionStatus = xhr.getResponseHeader('sessionstatus');
if(sessionStatus == 'timeout' && flag ) {
flag = false;
var top = getTopWinow();
$.TipsBox.Alert("由于您长时间没有操作, session已过期, 请重新登录","error","",function(){
//成功回调
flag = true;
top.location.href = path+"/sys/login.htm";
});
}
}
});
/**
* 在页面中任何嵌套层次的窗口中获取顶层窗口
* @return 当前页面的顶层窗口对象
*/
function getTopWinow(){
var p = window;
while(p != p.parent){
p = p.parent;
}
return p;
}
*****************************************************************
$.ajaxSetup详解,参数另见 ‘$.ajax’
![](https://i-blog.csdnimg.cn/blog_migrate/19bd91b9b79356859acd494bfa2bb387.png)