Session超时后,Ajax请求处理方式

传统的基于B/S的应用中,Session会话超时后通常是跳转到应用的首页,但Ajax请求的处理方式有些不同,下面简单介绍一下Ajax请求的Session超时处理(超时后返回首页)

1.首先创建一个Filter

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxSessionTimeoutFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		// 判断session里是否有用户信息
		if (req.getSession().getAttribute("SPRING_SECURITY_CONTEXT") == null){
			// 如果是ajax请求响应头会有,x-requested-with;
			if (req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
				res.setStatus(911);//表示session timeout
			}else{
				chain.doFilter(req, res);
			}
		}else{
			chain.doFilter(req, res);
		}
	}

	public void init(FilterConfig chain) throws ServletException {

	}
}

2.在web.xml中增加以下配置


	ajaxSessionTimeout
	org.tshark.framework.web.filter.AjaxSessionTimeoutFilter


	ajaxSessionTimeout
	/*

3.设置Ajax调用全局参数

$.ajaxSetup({
	contentType : "application/x-www-form-urlencoded;charset=utf-8",
	complete : function(xhr, textStatus) {
		$.ts.hideLoading();
		//session timeout
		if (xhr.status == 911) {
			window.location = rootPath + "/";//返回应用首页
			return;
		}
	}
});


你可能感兴趣的:(Java)