Session Handling in Jsf Example


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 JsfSession implements PhaseListener {    
	public void afterPhase(PhaseEvent event) {        
		//Do anything    
	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();            
			try {      
				} catch (Throwable t) {       
					throw new FacesException("Session timeout, Login again to continue", t);            
	public PhaseId getPhaseId() {        
		return PhaseId.RESTORE_VIEW;    

Add the above created package to faces-config.xml file,


And finally add the session timeout in web.xml file,


Note: 5 means 5 minutes here.

Recommended Books:

2,085 total views, 2 views today

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.