在過濾器中寫入如下方法: 復制代碼 代碼如下:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httprequest = (HttpServletRequest) request;
HttpServletResponse httpresponse = (HttpServletResponse) response;
String url = httprequest.getRequestURL().toString();
if (httprequest.getSession()== null) {
if (httprequest.getHeader("x-requested-with") != null
&& httprequest.getHeader("x-requested-with").equals(
"XMLHttpRequest")) { // ajax請求
httpresponse.setHeader("sessionstatus", "timeout");
} else {
httpresponse.sendRedirect("/test/index.jsp");
return;
}
} else {
chain.doFilter(request, response);
}
}
這樣,如果session超時,而且是ajax請求,就會在響應頭裡,sessionstatus有一個timeout;
再用一個全局的方法來處理,session超時要跳轉的頁面。
jquery 可以用$.ajaxSetup 方法,ext也有類似的方法: 復制代碼 代碼如下:
//全局的ajax訪問,處理ajax清求時sesion超時
$.ajaxSetup({
contentType : "application/x-www-form-urlencoded;charset=utf-8",
complete : function(XMLHttpRequest, textStatus) {
var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus"); // 通過XMLHttpRequest取得響應頭,sessionstatus,
if (sessionstatus == "timeout") {
// 如果超時就處理 ,指定要跳轉的頁面
window.location.replace("/test/index.jsp");
}
}
});