search
HomeWeb Front-endJS TutorialHow to handle session failure when ajax accesses it

This time I will show you how to handle the failure of ajax access to Session, and what are the precautions for handling the failure of ajax access to Session. The following is a practical case, let's take a look.

Recently due to a project, the module switched to ajax request data. When the Session failed, there was no return value after the ajax request, only the response html: Ajax is now widely used in Web projects, almost everywhere, which brings another question: What should you do when an Ajax request encounters a Session timeout?

Obviously, the traditional page jump is no longer applicable here, because the Ajax request is initiated by the XMLHTTPRequest object rather than the browser. The page jump after the verification fails cannot be reflected in the browser because the server returns (or output) information is 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 under the control of JavaScript, then do we Can JavaScript be used to complete page jumps?

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

The above two pictures are using Intercepted by Firefox's Firebug, the former is ordinary HTTP request header information; the latter is the request header information of Ajax request. Pay attention to the part surrounded by the red box 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. This is what we can take advantage of.

Let’s take a look at how the code is implemented.

InterceptorFilter

When using Struts2, we generally use Interceptor (interceptor) to intercept permission issues.

Part of the interceptor code:

public String intercept(ActionInvocation invocation) throws Exception {
    // TODO Auto-generated method stub
    ActionContext 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; 
    //获取session
    Map session = ac.getSession();
    //判断session是否存在及session中的user信息是否存在,如果存在不用拦截
    if(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());
      //访问路径
      String visitURL = invocation.getProxy().getNamespace() + "/" + invocation.getProxy().getActionName() + Constants.FE_STRUTS_ACTION_EXTENSION;
      visitURL = visitURL.substring(1);
      Map<string> authMap = (Map<string>) session.get(Constants.FE_SESSION_BG_AUTH);
      Map<integer> actionMap = (Map<integer>) authMap.get(Constants.FE_BG_ACTIONMAP);
      if(actionMap != null && !actionMap.isEmpty() && visitURL != null){
        if (actionMap.containsValue(visitURL)) {
          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.setHeader("sessionstatus", "timeout"); 
        response.sendError(518, "session timeout."); 
        return null;
      }else {
        
        String actionName = invocation.getProxy().getActionName();
        System.out.println(actionName);
        //如果拦截的actionName是loginUI或login,则不做处理,否则重定向到登录页面
        if (StringUtils.isNotBlank(actionName) && actionName.equals(Constants.FE_BG_LOGINUI)) {
          return invocation.invoke();
        }else if(StringUtils.isNotBlank(actionName) && actionName.equals(Constants.FE_BG_LOGIN)){
          return invocation.invoke();
        }else{
          String login = basePath + "/" + Constants.FE_BG_LOGIN_NAMESPACE + "/" + Constants.FE_BG_LOGINUI + Constants.FE_STRUTS_ACTION_EXTENSION;
//        System.out.println("+++++++++++++++++++++++++++basePath:"+basePath);
//        response.sendRedirect(login);
          PrintWriter out = response.getWriter();
//        out.println(""); 
//        out.println("<script>"); 
//        out.println("window.open (&#39;"+login+"&#39;,&#39;_top&#39;);"); 
//        out.println("</script>"); 
//        out.println("");
          out.write("<script>window.open(&#39;"+login+"&#39;,&#39;_top&#39;);</script>");
          return null;
        }
      }
    }
    
  }</integer></integer></string></string>
As can be seen from the above code, when the Session verification fails (that is, the Session times out), we obtain the request header information X through HttpServletRequest If the value of -Requested-With is not empty and equal to XMLHttpRequest, then it means that the request is an Ajax request. Our response is to add a header information (customized) to the response and return the response object HttpServletResponse to the server

Error message (518 status is defined by yourself); these messages will be received by JavaScript, so the following work will be done by JavaScript code.

Javascript code

$.ajaxSetup method is used to set the default options for AJAX requests. We can think of it as a global option setting, so it can Add this code to an external JS file and reference it on the required page.

/**
 * 设置未来(全局)的AJAX请求默认选项
 * 主要设置了AJAX请求遇到Session过期的情况
 */
$.ajaxSetup({
  type: 'POST',
  complete: function(xhr,status) {
    var sessionStatus = xhr.getResponseHeader('sessionstatus');
    if(sessionStatus == 'timeout') {
      var top = getTopWinow();
      var yes = confirm('由于您长时间没有操作, session已过期, 请重新登录.');
      if (yes) {
        top.location.href = '/skynk/index.html';      
      }
    }
  }
});
/**
 * 在页面中任何嵌套层次的窗口中获取顶层窗口
 * @return 当前页面的顶层窗口对象
 */
function getTopWinow(){
  var p = window;
  while(p != p.parent){
    p = p.parent;
  }
  return p;
}
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Ajax implements the function of file upload with progress bar effect

How to use the Rating control in AjaxToolKit

The above is the detailed content of How to handle session failure when ajax accesses it. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools