Handling Ajax session expired requests (reproduced)

The problem arises:  

  Today Ajax is widely used in web projects, almost everywhere.

  Sometimes I encounter such a problem: what should I do when the Ajax request encounters the Session timeout?

  Obviously, the traditional page jump is no longer applicable here, because the Ajax request is initiated by the XMLHTTPRequest object instead of the browser, and the page jump after the validation fails cannot be reflected in the browser, because the information returned (or output) by the server Received by JavaScript (XMLHTTPRequest object).

  So how should this situation be handled?

Solution to the problem:

  Since the message returned by the server is received by the XMLHTTPRequest object, and the XMLHTTPRequest object is under the control of JavaScript, can we use JavaScript to complete page jumps?

  Of course you can, and it's easy to do! But one thing, we need to judge whether the HTTP request is an Ajax request (because AJAX requests and ordinary requests need to be processed separately), how to judge this? In fact, Ajax requests are different from ordinary HTTP requests, which are reflected in the header information of HTTP requests, as follows:



 

 

The above two pictures are intercepted by Firefox's Firebug, the former is the request header information of Ajax request; the latter is the ordinary HTTP request header information. Pay attention to the part circled by the red frame in the first picture. This is where the Ajax request is different from the ordinary request. The AJAX request header contains the X-Requested-With information, and its value is XMLHttpRequest, which is where we can use it.

Javascript code

The $.ajaxSetup method is used to set the default options for AJAX requests, which can be considered as global option settings, so this code can be mentioned in the external JS file and referenced on the required page.

copy code
/**
 * Set default options for future (global) AJAX requests
 * Mainly set the AJAX request to encounter the Session expired
 */
$.ajaxSetup({
    type: 'POST',
    complete: function(xhr,status) {
        var sessionStatus = xhr.getResponseHeader( ' sessionstatus ' );
         if (sessionStatus == ' timeout ' ) {
             var top = getTopWinow();
             var yes = confirm( ' The session has expired due to inactivity, please log in again. ' );
             if (yes) {
                top.location.href = '/skynk/index.html';            
            }
        }
    }
});

/**
 * Get the top-level window in any nested window in the page
 * @return the top-level window object of the current page
 */
function getTopWinow(){
    var p = window;
    while(p != p.parent){
        p = p.parent;
    }
    return p;
}
copy code

Part of the code of the interceptor:

copy code
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * Login filter
 * Have 2 conditions to judge whether the session is invalid and whether the user is logged in
 * If it is an ajax request, set the session timeout
 * @author Merlin.Ma
 *
 */
public class LoginFilter implements Filter{
  private String redirectUrl = "/login.html";
  private String sessionKey = "userName";
  @Override
  public void destroy() {
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse rep = (HttpServletResponse) response;
    HttpSession session = req.getSession();
    if( session == null || session.getAttribute(sessionKey) == null){
      //如果判断是 AJAX 请求,直接设置为session超时
      if( req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equals("XMLHttpRequest") ) {
        rep.setHeader("sessionstatus", "timeout"); 
      } else {
        rep.sendRedirect( req.getContextPath() + redirectUrl);
      }
    }else {
      chain.doFilter(request, response);
    }   
  }
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    String url = filterConfig.getInitParameter("redirectUrl");
    String key = filterConfig.getInitParameter("sessionKey");
    redirectUrl = url == null? redirectUrl:url;
    sessionKey = key == null ? sessionKey : key ;
  }
}
copy code

It can be seen from the above code that when the session verification fails (ie the session times out), we obtain the value of the request header information X-Requested-With through HttpServletRequest. If it is not empty and equal to XMLHttpRequest, it means that the request is an Ajax request. , our response is to add a header information (custom) to the response and make the response object HttpServletResponse return server error information (518 status is freely defined by ourselves); these information will be received by JavaScript, then the following work will be done by JavaScript code too.

 

 

Original address: https://www.cnblogs.com/renxiaoren/p/5411657.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326145883&siteId=291194637