Perfect solution Ajax Access encountered session failure _ajax related issues

Source: Internet
Author: User

Recently because of a project, module switching to AJAX request data, when the session failed, after the AJAX request no return value, only the response of Html:

Now that Ajax is widely used in Web projects, almost everywhere, this poses another problem: what should I do when an AJAX request encounters a session timeout?

Obviously, the traditional page jump does not apply here, because the AJAX request is the XMLHttpRequest object originated instead of the browser, the page jump after the failure of validation failed to respond to the browser, Because the server returned (or output) information was received by JavaScript (XMLHttpRequest object).

So how should 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 achieve! But one thing we need to determine is whether an HTTP request is an AJAX request (because AJAX requests and ordinary requests need to be handled separately). In fact, Ajax requests are different from ordinary HTTP requests, which are reflected in the header information of the HTTP request, as follows:

The above two images are intercepted using Firefox's Firebug, which is a common HTTP request header, and the request header information for AJAX requests. Note that the first picture is circled by the red box, which is the difference between the AJAX request and the ordinary request, the AJAX request header with X-requested-with information, the value of XMLHttpRequest, which is the place we can use.

Let's look at how the code is implemented.

Interceptor Filter

When using STRUTS2, we typically use interceptor (interceptors) to intercept permissions issues.

Interceptor Part code:

Public String intercept (actioninvocation invocation) throws Exception {//TODO auto-generated method stub Action
    Context ac = Invocation.getinvocationcontext ();
    HttpServletRequest request = (httpservletrequest) ac.get (strutsstatics.http_request);
    String RequestType = Request.getheader ("X-requested-with");
    System.out.println ("+++++++++++++++++++++++reqesttype:" +requesttype);
HttpServletResponse response = (httpservletresponse) ac.get (strutsstatics.http_response);
    String basepath = Request.getcontextpath (); 
    String path = Request.getcontextpath (); 
    String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path;
    Gets the session Map session = Ac.getsession (); Determines whether the session exists and the USER information in the session exists, if there is no need to intercept if (session!= null && session.get (constants.fe_session_bg_user )!= null && session.get (Constants.fe_session_bg_auth)!= null) {System.out.println (Invocation.getproxy (). GE TactionnamE () + "++++++++++++++++++++++++");
      System.out.println ("namespace:" +invocation.getproxy (). GetNamespace ()); Access path String Visiturl = Invocation.getproxy (). GetNamespace () + "/" + Invocation.getproxy (). Getactionname () + Consta Nts.
      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); if (actionmap!= null &&!actionmap.isempty () && visiturl!= null) {if Actionmap.containsvalue (vis
          Iturl)) {System.out.println (visiturl+ "-----------------------");
        return Invocation.invoke ();
          } else{String Forbidden = basepath + Constants.fe_bg_forbidden;
          Response.sendredirect (Forbidden);
        return null;
    } return Invocation.invoke (); }else{IF (Stringutils.isnotblank (RequestType) && requesttype.equalsignorecase ("XMLHttpRequest")) {Response.setHea 
        Der ("Sessionstatus", "timeout"); 
        Response.senderror (518, "Session timeout.");
      return null;
        }else {String actionname = Invocation.getproxy (). Getactionname ();
        System.out.println (ActionName); If the intercepted actionname is Loginui or login, it is not processed, otherwise redirected to the login page if (Stringutils.isnotblank (actionname) && Actionname.equa
        LS (Constants.fe_bg_loginui)) {return Invocation.invoke (); }else if (Stringutils.isnotblank (actionname) && actionname.equals (Constants.fe_bg_login)) {return invocat
        Ion.invoke (); }else{String login = basepath + "/" + Constants.fe_bg_login_namespace + "/" + Constants.fe_bg_loginui + Constan Ts.
Fe_struts_action_extension;
System.out.println ("+++++++++++++++++++++++++++basepath:" +basepath);
          Response.sendredirect (login); PrintwrITER out = Response.getwriter (); 
Out.println (" 

As can be seen from the above code, when session validation fails (that is, session timeout), we get the X-requested-with value of the request header information via httpservletrequest, if not null and equal to XMLHttpRequest, So this request is an AJAX request, and our response is to add a header (custom) message to the response and httpservletresponse the response object back to the server error message (518 State is defined by itself) ; This information will be received by JavaScript, so the following work will be done by JavaScript code.

JavaScript code

The $.ajaxsetup method is to set the AJAX request default option, we can think of the global option settings, so you can refer to this code in the external JS file, in the desired page reference.

/**
 * Set the Future (global) Ajax request default option
 * Mainly set the AJAX request encountered session expiration of the situation * * *
$.ajaxsetup ({
  type: ' POST ',
  Complete:function (xhr,status) {
    var sessionstatus = xhr.getresponseheader (' sessionstatus ');
    if (sessionstatus = = ' Timeout ') {
      var top = Gettopwinow ();
      var yes = confirm (' Because you have no action for a long time, session has expired, please login again. ');
      if (yes) {
        top.location.href = '/skynk/index.html ';      
      }}}
);

/**
 * Get the top-level window in any nested level window in the page
 * @return The top-level window object of the current page
/function Gettopwinow () {
  var p = window;< C23/>while (P!= p.parent) {
    p = p.parent;
  }
  return p;
}

The above perfect solution to the AJAX access session failure is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.