Recently due to a project, the module switched to AJAX request data, when the session expires, Ajax request after no return value, only the response of Html:
Now that Ajax is widely used in Web projects, almost everywhere, there is another question: what should I do when the AJAX request encounters a session timeout?
Obviously, the traditional page jump is not applicable here, because the AJAX request is XMLHttpRequest Object-initiated instead of the browser, after the verification failed page jump cannot reflect the browser, Because the server returns (or outputs) the information is received by the JavaScript (XMLHttpRequest object).
So how do we deal with this situation?
Method
Since the message returned by the server is received by the XMLHttpRequest object, and the XMLHttpRequest object is in the control of JavaScript, can we use JavaScript to complete the page jump?
Sure, and it's easy to implement! But one thing, we need to determine if the HTTP request is an AJAX request (because the AJAX request and the ordinary request need to be handled separately), how can this be judged? In fact, the AJAX request is different from the normal HTTP request, which is reflected in the header information of the HTTP request, as follows:
The above two pictures are intercepted with the Firebug of Firefox, the former is the normal HTTP request header information, the latter is the request header information of Ajax request. Note that the first picture is circled by a red frame, which is where the AJAX request differs from the normal request, with the X-requested-with information in the AJAX request header with a value of XMLHttpRequest, which is where we can use it.
Let's take a look at how the code is implemented.
Interceptor Filter
When using STRUTS2, we generally use interceptor (interceptors) to intercept permissions issues.
Interceptor Part code:
1Public String intercept (actioninvocation invocation)ThrowsException {2//TODO auto-generated Method Stub3 Actioncontext AC =Invocation.getinvocationcontext ();4 HttpServletRequest request =(httpservletrequest) Ac.get (strutsstatics.http_request);5 String RequestType = Request.getheader ("X-requested-with");6 System.out.println ("+++++++++++++++++++++++reqesttype:" +RequestType);7 HttpServletResponse response =(HttpServletResponse) Ac.get (strutsstatics.http_response);8//String basepath = Request.getcontextpath ();9 String Path =Request.getcontextpath ();Ten String BasePath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +Path11//Get sessionMap session =Ac.getsession ();13//Determine if the session exists and whether the user information exists in the session, if there is no interception14if (Session! =Null && session.get (constants.fe_session_bg_user)! =Null && session.get (constants.fe_session_bg_auth)! =Null){System.out.println (Invocation.getproxy (). Getactionname () + "++++++++++++++++++++++++");System.out.println ("namespace:" +Invocation.getproxy (). GetNamespace ());17//Access pathString Visiturl = Invocation.getproxy (). GetNamespace () + "/" + Invocation.getproxy (). Getactionname () +Constants.fe_struts_action_extension;Visiturl = visiturl.substring (1);map<string, object> Authmap = (map<string, object>) Session.get (Constants.fe_session_bg_auth);Map<integer, string> ActionMap = (Map<integer, string>) Authmap.get (CONSTANTS.FE_BG_ACTIONMAP);22if (actionmap! =Null &&!actionmap.isempty () && visiturl! =Null){23If(Actionmap.containsvalue (Visiturl)) {System.out.println (visiturl+ "-----------------------");25ReturnInvocation.invoke ();26}Else{String Forbidden = BasePath +Constants.fe_bg_forbidden;28Response.sendredirect (Forbidden);29ReturnNull;30}31}32ReturnInvocation.invoke ();33}Else{34if (Stringutils.isnotblank (RequestType) && requesttype.equalsignorecase ("XMLHttpRequest")){Response.setheader ("Sessionstatus", "timeout");Response.senderror (518, "Session timeout."));37ReturnNull;38}Else{39ActionName String =Invocation.getproxy (). Getactionname ();41System.out.println (ActionName);42//If the intercepted actionname is Loginui or login, do not process, otherwise redirect to the login page43if (Stringutils.isnotblank (actionname) &&Actionname.equals (Constants.fe_bg_loginui)) {44ReturnInvocation.invoke ();45}Elseif (Stringutils.isnotblank (actionname) &&Actionname.equals (Constants.fe_bg_login)) {46ReturnInvocation.invoke ();47}Else{-String Login = BasePath + "/" + Constants.fe_bg_login_namespace + "/" + Constants.fe_bg_loginui +Constants.fe_struts_action_extension;49//System.out.println ("+++++++++++++++++++++++++++basepath:" +basepath);50//Response.sendredirect (login);Wuyi PrintWriter out =Response.getwriter ();52//Out.println ("53//Out.println ("<script>");54//Out.println ("window.open ('" +login+ "', ' _top ');");55 // Out.println (" </script> "); 56 // Out.println (" 57 out.write ("); 58 return null; 59 }60 }61 }62 63}
As can be seen from the above code, when the session validation fails (that is, the session timeout), we get the value of the request header information X-requested-with through HttpServletRequest, if it is not empty and equals XMLHttpRequest, So the request is an AJAX request, and our response is to add a header message (custom) to the response and httpservletresponse the response object back to the server error message (518 states are self-defined); This information will be JavaScript is received, then the following work is going to be done by JavaScript code.
JavaScript code
The $.ajaxsetup method is to set the default options for AJAX requests, which we can consider to be global option settings, so you can refer to the external JS file in the required page.
1/**2* Set Future (GLOBAL) Ajax request default options3* The main set of AJAX requests encountered when the session expired4*/5$.ajaxsetup ({6 Type: ' POST ',7 Complete:function(Xhr,status) {8var sessionstatus = xhr.getresponseheader (' Sessionstatus ');9if (sessionstatus = = ' Timeout ') {10var top =Gettopwinow ();11var yes = confirm (' The session has expired because you haven't been working for a long time, please sign in again. '));12If(yes) {Top.location.href = '/skynk/index.html ';14}15}16}17});1819/**2021 * @return the top-level window object of the current page 22 */23 function Gettopwinow () {24 var p = window; 25 while (P!= P.parent) {26 p = P.parent; }28 return P; 29}
Ajax Access encounters a session failure problem