JSF Session Timeout Handling

Here's my solution for session handling. When your session timed out, you will be redirected to the index page which is commonly the login page to login again.

package com.mypackage.web.session;

import javax.faces.FacesException;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class SessionPhaseListener implements PhaseListener {

private static final String homepage = "index.jsp";

@Override
public void afterPhase(PhaseEvent event) {
//Do anything
}

@Override
public void beforePhase(PhaseEvent event) {
FacesContext context = event.getFacesContext();
ExternalContext ext = context.getExternalContext();
HttpSession session = (HttpSession) ext.getSession(false);
boolean newSession = (session == null) || (session.isNew());
boolean postback = !ext.getRequestParameterMap().isEmpty();
boolean timedout = postback && newSession;
if (timedout) {
Application app = context.getApplication();
ViewHandler viewHandler = app.getViewHandler();
UIViewRoot view = viewHandler.createView(context, "/" + homepage);
context.setViewRoot(view);
context.renderResponse();
try {
viewHandler.renderView(context, view);
context.responseComplete();
} catch (Throwable t) {
throw new FacesException("Session timed out", t);
}
}
}

@Override
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
}

Once you created the class above that implements the PhaseListener, add this to you faces-config.xml. Note that the package name depends on your own Java packaging.
<lifecycle>
<phase-listener>com.mypackage.web.session.SessionPhaseListener</phase-listener>
</lifecycle>

6 comments:

  1. Thanks a lot man, you are the first one who really helped me in this annoying ViewState

    ReplyDelete
  2. Thanks a lot! this really did help me!

    ReplyDelete
  3. This helped me a lot... thank you for sharing this globally!

    ReplyDelete
  4. This is what i am looking for a long time. Thanks for such a great help. Now it is working fine.

    ReplyDelete
  5. This solutions is not working for me If tomcat security-constraint is setup

    ReplyDelete
  6. good code..problem here is the first request which is new is going to the time out page.

    And another problem is the the request parameter map which is true for both the cases. how can't affect session timeout??

    ReplyDelete