Ajax请求Session超时的处理

孤街醉人 提交于 2021-02-11 01:24:55

1、客户端的js处理(使用jqury)

<script type="text/javascript">
			//<![CDATA[  
		 	$(document).ajaxComplete(function(event, xhr, settings) {
				if(xhr.getResponseHeader("sessionstatus")=="timeOut"){
					if(xhr.getResponseHeader("loginPath")){
						window.location.replace(xhr.getResponseHeader("loginPath"));
					}else{
						alert("Request time out relogin plase !");
					}
				}
			}); 
			//]]>
		</script>

2、服务器端处理(filter中)

if(sessionTimeOut){
	//判断是否为ajax请求
		if (httpRequest.getHeader("x-requested-with") != null && httpRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
			HttpServletResponse httpResponse = (HttpServletResponse)response;
			httpResponse.addHeader("sessionstatus", "timeOut");
			httpResponse.addHeader("loginPath",loginUrl);
			filterChain.doFilter(request, response);//不可少,否则请求会出错
		}else{//不是ajax请求,超时直接重定向
			((HttpServletResponse) response).sendRedirect(loginUrl);
		}
	}


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!