Monday, May 12, 2014

Handling Session Timeout in AJAX requests for a JSF application


Handling sessions in a traditional GET / POST request has a standard way and the timeouts and accesses can be easily handled using a HTTP  Filter in the J2EE Web Applications. However when it comes to AJAX Requests in a J2EE environment, the AJAX requests (being relatively lately integrated in JSF) does not see any response being sent back when the Session timesout and the user is stuck frozen on the screen without any clue of what has happened.

 

Following can be done to handle session timeout in AJAX requests and redirect the user.

 

1.    Add a HTTP Filter in the Web Application which should tap all the requests received by the Web Application

 

      <filter>
            <filter-name>Authentication Filter</filter-name>
            <filter-class>com.test.AuthenticationFilter</filter-class>
      </filter>
      <filter-mapping>
            <filter-name>Authentication Filter</filter-name>
            <servlet-name>Faces Servlet</servlet-name>
            <url-pattern>/*</url-pattern>
            <dispatcher>REQUEST</dispatcher>
            <dispatcher>FORWARD</dispatcher>
      </filter-mapping>

 

 

2.    Check whether the request is an AJAX Request in the AuthenticationFilter class. This could be ensured by checking a special parameter in HTTP Request which indicates that it is an AJAX request. Following method returns whether the request is AJAX Request.

 

private boolean isAjax(HttpServletRequest req) {
  if ("partial/ajax".equals(req.getHeader("faces-request"))) {
    return true;
  } else if ("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
    return true;
  }
  return false;
}

 

 

3.    Return a custom JavaScript or page redirect code back in the response so let the user know that the session has expired and he/she needs to login again

 

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
  HttpServletResponse resp1 = (HttpServletResponse) response;
  // Check if the request is AJAX request
  if (isAjax(httpRequest)) {
    resp1.getWriter().write("<?xml version='1.0' encoding='UTF-8'?>" +
                  "<partial-response>" +
                  "<changes>" +
                  "<eval>alert('Invalid session.');" +
                  "window.location.href='" + path + "';" +
                  "</eval>" +
                  "</changes>" +
                  "</partial-response>");
  } else {
    // Do usual redirect if the request is not an AJAX request
    httpResponse.sendRedirect(path);
  }
 
}

 
This is how I controlled AJAX requests in my application. Any alternative ideas or suggestions are most welcome.

No comments:

Post a Comment