Boris Lam

About Boris Lam

Boris is an experienced Java developer with in Hong Kong. His expertise is in Java EE technology, object-oriented application development, and the use of open source frameworks (e.g. Spring , Apache MyFaces). In recent years, he is primarily involved in framework development and architectural design in serveral Government related software development projects.

Session Timeout Handling on JSF AJAX request

Session Timeout Handling on JSF AJAX request

When we develop JSF application with AJAX behaviour, we may experience the problem in handling timeout scenario of Ajax request. For example, if you are using J2EE Form-based authentication, a normal request should be redirected to the login page after session timeout. However, if your request is AJAX, the response could not be treated properly on the client-side. User will remain on the same page and does not aware that the session is expired.

Many people proposed solution for this issue. The followings are two of possible solutions involve the use of Spring security framework:

1. Oleg Varaksin’s post
2. Spring Security 3 and ICEfaces 3 Tutorial

Yet, some applications may just using simple mechanism to stored their authentication and authorization information in session. For those application that is not using Spring Security framework, how can they handle such problem? I just modified the solution proposed by Oleg Varaksin a bit as my reference.

First, create a simple session scoped JSF managed bean called ‘MyJsfAjaxTimeoutSetting’.

The main purpose of this POJO is just to allow you to configure the redirect url after session timeout in faces-config.xml. You may not need this class if you do not want the timeout URL to be configurable.

public class MyJsfAjaxTimeoutSetting {

 public MyJsfAjaxTimeoutSetting() {

 private String timeoutUrl;

 public String getTimeoutUrl() {
  return timeoutUrl;

 public void setTimeoutUrl(String timeoutUrl) {
  this.timeoutUrl = timeoutUrl;


Second, create a PhaseListener to handle the redirect of Ajax request.

This PhaseListener is the most important part of the solution. It re-creates the response so that the Ajax request could be redirect after timeout.

import org.borislam.util.FacesUtil;
import org.borislam.util.SecurityUtil;
import javax.faces.FacesException;
import javax.faces.FactoryFinder;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;

public class MyJsfAjaxTimeoutPhaseListener implements PhaseListener

 public void afterPhase(PhaseEvent event)

 public void beforePhase(PhaseEvent event)
  MyJsfAjaxTimeoutSetting timeoutSetting = (MyJsfAjaxTimeoutSetting)FacesUtil.getManagedBean('MyJsfAjaxTimeoutSetting');
  FacesContext fc = FacesContext.getCurrentInstance();
  RequestContext rc = RequestContext.getCurrentInstance();
  ExternalContext ec = fc.getExternalContext();
  HttpServletResponse response = (HttpServletResponse) ec.getResponse();
  HttpServletRequest request = (HttpServletRequest) ec.getRequest();

  if (timeoutSetting ==null) {
   System.out.println('JSF Ajax Timeout Setting is not configured. Do Nothing!');
   return ;

  UserCredential user = SecurityUtil.getUserCredential(); 
  // You can replace the above line of code with the security control of your application.
  // For example , you may get the authenticated user object from session or threadlocal storage.
  // It depends on your design.

  if (user==null) {
   // user credential not found. 
   // considered to be a Timeout case

   if (ec.isResponseCommitted()) {
    // redirect is not possible


       if ( 
     ( (rc!=null &&  RequestContext.getCurrentInstance().isAjaxRequest())
     || (fc!=null && fc.getPartialViewContext().isPartialRequest()))
      && fc.getResponseWriter() == null
       && fc.getRenderKit() == null) {


        RenderKitFactory factory = (RenderKitFactory)  

        RenderKit renderKit = factory.getRenderKit(fc,

        ResponseWriter responseWriter =
     response.getWriter(), null, request.getCharacterEncoding());

        ec.redirect(ec.getRequestContextPath() + 
          (timeoutSetting.getTimeoutUrl() != null ? timeoutSetting.getTimeoutUrl() : ''));     

   } catch (IOException e) {
    System.out.println('Redirect to the specified page '' + 
      timeoutSetting.getTimeoutUrl() + '' failed');
    throw new FacesException(e);
  } else {
   return ; //This is not a timeout case . Do nothing !

 public PhaseId getPhaseId()
  return PhaseId.RESTORE_VIEW;


The details of the FacesUtil.getManagedBean(‘MyJsfAjaxTimeoutSetting’) is shown below:

public static Object getManagedBean(String beanName) {

     FacesContext fc = FacesContext.getCurrentInstance();
     ELContext elc = fc.getELContext();
     ExpressionFactory ef = fc.getApplication().getExpressionFactory();
     ValueExpression ve = ef.createValueExpression(elc, getJsfEl(beanName), Object.class);
     return ve.getValue(elc);


As said before, the purpose of the session scoped managed bean, MyJsfAjaxTimeoutSetting, is just to allow you to make the timeoutUrl configurable in your faces-config.xml.


Most importantly, add the PhaseListener in your faces-config.xml.

<phase-listener id="JSFAjaxTimeoutPhaseListener">                             </phase-listener>

If you are using spring framework, you could managed the MyJsfAjaxTimeoutSetting in Spring with the help of SpringBeanFacesELResolver. Then, you can use the following configuration.

<bean id="MyJsfAjaxTimeoutSetting" class="" scope="session">   
 <property name="timeoutUrl" value="/">


Reference: Session Timeout Handling on JSF AJAX request from our JCG partner Boris Lam at the Programming Peacefully blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

One Response to "Session Timeout Handling on JSF AJAX request"

  1. devender says:

    Nice tutorial .It has solved my problem .Kepp going on.

Leave a Reply

− 1 = three

Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: