ExtJS以及JQuery异步请求Session过期解决方案

ExtJS以及JQuery异步请求Session过期解决方案

 
最近在开发中遇到这样的问题,当Session过期后,通过拦截器判断过期并通过response.sendRedirect(request.getServletContext()+"/login.jsp")重定位到登录界面,但是因为大部分前后台的交互是通过Ajax进行的异步请求,这种做法只能是该请求没有任何的实际相应,但是不能重定位到登录界面。
 
然后就想能不能对异步请求,在其返回的时候进行统一的前端拦截,判断如果responseText符合{timeout: true, redirectUri:'/ServletContext/login.jsp'},也就是说timeout为true则自动重定位到redirectUri对应的页面。
 
通过网上查找找到如下解决方案:
鉴于一下两个特性:
1、Ext.Ajax是单实例对象(非常重要,全局单一Ext.Ajax实例!) 
2、注册Ext.Ajax的requestcomplete事件,每个ajax请求成功后首先响应该事件(概念类似spring的aop拦截)。
首先在公用的脚本文件里增加如下两端内容:
  1.  1 //通过Ext封装的ajax请示时,默认增加请求头
     2 //或者可以使用所有ajax请求都带有的x-request-with:XMLHttpRequest头信息
     3 //如果既有Ext又有Jquery而且要区分处理,则需要这种方式
     4 Ext.Ajax.defaultHeaders = {
     5     'Request-By': 'Ext'    //标识ajax请求
     6 };
     7 //当响应时,自动拦截并判断如果符合timeout为true就重定位到redirectUri
     8 Ext.Ajax.on('requestcomplete',checkSessionStatus, this);         
     9 function checkSessionStatus(conn,response,options){
    10     var json = Ext.decode(response.responseText);
    11     if(typeof json == 'object' 
    12         && json.timeout){
    13         Ext.Msg.alert("提示","登入超时,系统将自动跳转到登陆页面,请重新登入!",function(){
    14             top.window.location.href = json.redirectUri;
    15         });
    16     }      
    17 } 
后台拦截器进行如下修改:
  1.  1 String vsResuqestBy = request.getHeader("Request-By");
     2 String redirectUri = request.getContextPath() + "/login.jsp";
     3 //如果是Ext的ajax请求则返回响应{"timeout":true,"redirectUri":"/ServletContext/login.jsp"}
     4 //否则,则直接重定为到login.jsp
     5 if(vsResuqestBy != null && "Ext".endsWith(vsResuqestBy)){
     6     response.getWriter().write("{"timeout":true,"redirectUri":""+redirectUri+""}");
     7 }
     8 else{
     9     response.sendRedirect(redirectUri);
    10 }  
OK,到此问题解决,考虑到还有一个项目是jquery的,所以也顺便研究了一下,解决思路如下,只描述出前台的,后台跟上面类似,就不赘述了。
前台Jquery在公共脚本文件中增加:
  1.  1 $.ajaxSetup({
     2     headers: {
     3         'Request-By': 'Jquery'
     4     }
     5 });
     6 
     7 $.ajaxComplete(function(event,xhr,settings){
     8     var json = eval('('+xhr.responseText+')');
     9     if(typeof json == 'object' 
    10         && json.timeout){
    11         alert("登入超时,系统将自动跳转到登陆页面,请重新登入!");
    12         top.window.location.href = json.redirectUri;
    13     } 
    14 });

本文档参考了lym6520viczhu的思路,感谢。
   





原文地址:https://www.cnblogs.com/boulder/p/3926835.html