Session Handling in Jsf Example

JsfSession.java:

package com.javadomain.in;

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 {    
	@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();            
			context.renderResponse();            
			try {      
				ext.redirect("/index.jsp");
				context.responseComplete();
				} catch (Throwable t) {       
					throw new FacesException("Session timeout, Login again to continue", t);            
					}        
			}    
		}    
	@Override    
	public PhaseId getPhaseId() {        
		return PhaseId.RESTORE_VIEW;    
		}
}

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

<lifecycle>
      <phase-listener>com.javadomain.in.JsfSession</phase-listener>
</lifecycle>

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

<session-config>
	<session-timeout>5</session-timeout>
</session-config>

Note: 5 means 5 minutes here.

Recommended Books:

1,079 total views, 1 views today

Leave a Reply

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