利用AJAX重寫,解決session超時,ajax跳轉問題

小弟第一次發帖,最近爲了解決這個問題查了很久,終於解決了,不一定很好,各位看看吧。

因爲ajax無法執行攔截器的跳轉主頁響應,所以跳轉只能寫在前臺,但是爲了不改動已經寫好的代碼,只能進行統一設置,而ajaxSetup的統一設置只是缺省設置,不太好用,因此使用ajax重寫是最好的解決辦法。

jQuery(function($){  
	// 備份jquery的ajax方法    
	var _ajax=$.ajax;  
	// 重寫ajax方法,先判斷登錄在執行error函數   
	$.ajax=function(opt){  
		var _error = opt && opt.error || function(a, b){};  
		var _opt = $.extend(opt, {  
			error:function(data, textStatus){  
			   if(data.status==401){
					alert("登錄超時,請重新登錄!");
  					storage.clear();//清空sessionStorage(類似cookie的東西)
 					window.location.replace("/index.html");
			   }else{
					_error(data, textStatus);    
			   }
			}    
		});  
		_ajax(_opt);  
	};  
}); 
如上代碼,當攔截器返回false時,會執行ajax的error回調函數,因此重寫的error是先判斷error是不是因爲session失效,是的話就跳轉,不是的話再執行error函數。


順便把攔截器貼上來吧,不知道能不能幫到大家

public class LoginInterceptor implements HandlerInterceptor {
	
    @Autowired
    private LoginService loginService;
	
    @Override  
    public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler) throws Exception {  
    	System.out.println(">>>LoginInterceptor>>>>>>>登錄校驗攔截器開始執行>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    	
    	//獲取請求的URL  
        String url = request.getRequestURI();  
        System.out.println("------------------------------url:"+url+"------------------------------");
        //設置例外url  
        if(url.indexOf("login")>=0 || url.indexOf("menu")>=0 || url.indexOf("error")>=0){  
            return true;  
        }  
        
        //獲取Session  
        HttpSession session = request.getSession();  
        Long uid = (Long)session.getAttribute("uid");  
        String guid = (String)session.getAttribute("guid");  
       // System.out.println("uid:"+uid+"\nguid:"+guid);
        if (loginService == null) {//解決service爲null無法注入問題 
			System.out.println("loginService is null!!! don't worry,we will fixed it");
			BeanFactory factory = WebApplicationContextUtils
					.getRequiredWebApplicationContext(request
							.getServletContext());
			loginService = (LoginService) factory.getBean("loginService");
	}
        try {
			if (uid != null) {
				List guidList = loginService.findGuidByUid(uid);
				if (guid.equals(guidList.get(0).toString())) {
					return true;
				}else{//隨機驗證碼匹配失敗的
					/**暫無特殊處理*/
				}
			}
	} catch (Exception e) {
			System.out.println(e.getMessage());
	}
	//session中沒有信息的,跳轉到主頁 
        if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){  
             response.setStatus(401);
        }else{
        	request.getRequestDispatcher("/index.html").forward(request, response);  
        }
        return false;  
    }  
      
    @Override  
    public void postHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler,  
            ModelAndView modelAndView) throws Exception {  
    	// System.out.println(">>>LoginInterceptor>>>>>>>請求處理之後進行調用,但是在視圖被渲染之前(Controller方法調用之後)");
          
    }  
    @Override  
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex)  
    throws Exception {  
    	//System.out.println(">>>LoginInterceptor>>>>>>>在整個請求結束之後被調用,也就是在DispatcherServlet 渲染了對應的視圖之後執行(主要是用於進行資源清理工作)");
          
    }  
		  
		   
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章