jQuery ajax请求处理session过期问题

后台扩展一个filter,判断session过期的代码需要自己写,我这里直接就认为session过期了

 

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		String xmlhttprequest = request.getHeader("X-Requested-With");
		if("XMLHttpRequest".equalsIgnoreCase(xmlhttprequest)) { // ajax request
			
			// 判断是否是session过期,如果是执行下边的代码
			try {  
	            response.setCharacterEncoding("UTF-8");  
	            response.setContentType("text/json");  
	            response.setDateHeader("Expires", 0);  
	            PrintWriter out = response.getWriter();  
	  
	            out.println("{\"sessionTimeout\": true}");  
	  
	            out.flush();  
	            out.close();  
	            
	            return;
	        } catch (IOException e) { 
	        	System.out.println(e);
	        } 
		}
		chain.doFilter(req, res);
	}

 客户端对jquery的ajax处理做扩展,代码如下

 

(function() {
	var oldajaxfuc = jQuery.ajax;
	jQuery.extend({
		ajax: function( url, options ){
			// If url is an object, simulate pre-1.5 signature
			if ( typeof url === "object" ) {
				options = url;
				url = undefined;
			}
			
			var oldSuccessFunc = options.success;
			options.success = function(ret) {
				if(ret.sessionTimeout) {
					alert("Session timeout");
					return;
				} else {
					oldSuccessFunc.apply(this, arguments);
				}
			}
			
			oldajaxfuc(url, options);
		}
	});
})();
 

你可能感兴趣的:(jQuery ajax)