当前位置: 代码迷 >> Ajax >> jQuery ajax请求处理session过期有关问题
  详细解决方案

jQuery ajax请求处理session过期有关问题

热度:382   发布时间:2012-09-23 10:28:11.0
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);
		}
	});
})();
?
  相关解决方案