JSF Phase Listener

From Foochal

Jump to: navigation, search

Contents

Loading the first page of a JSF application

The first page of a JSF application is rendered by typing a URL, such as,

http://localhost:8080/myjsfapp/index.jsf

The following phases are invoked when this request goes to the JSF controller:

  1. RESTORE_VIEW
  2. RENDER_RESPONSE

Clicking a button or a link on a JSF page

The following phases are invoked when this request goes to the JSF controller:

  1. RESTORE_VIEW
  2. APPLY_REQUEST_VALUES
  3. PROCESS_VALIDATIONS
  4. UPDATE_MODEL_VALUES
  5. INVOKE_APPLICATION
  6. RENDER_RESPONSE

Writing a custom phase listener

Writing a phase listener is equivalent to writing a Servlet filter. You need to write a class which implements the javax.faces.event.PhaseListener interface. The you should implement the getPhaseId() method to return the Phase ID for which you want your listener to listener. There is a special Phase Id called ANY_PHASE which registers your listener for all phases. Once registered, your listener's beforePhase() and afterPhase() methods will be called by the framework.

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class JsfPhaseListener implements PhaseListener {
	public void afterPhase(PhaseEvent phaseEvent) {
		PhaseId phaseId = phaseEvent.getPhaseId();

		// login user after applying model values
		if (phaseId == PhaseId.RESTORE_VIEW) {
			FacesContext facesContext = phaseEvent.getFacesContext();
			JsfController jsfController = (JsfController) facesContext
					.getApplication().createValueBinding("#{controller}")
					.getValue(facesContext);
			
			// restore the user from cookie
			jsfController.restoreUserFromCookieToSession();
		}
	}

	public void beforePhase(PhaseEvent phaseEvent) {
		PhaseId phaseId = phaseEvent.getPhaseId();
	}

	public PhaseId getPhaseId() {
		return PhaseId.ANY_PHASE;
	}
}

Adding your PhaseListener to your faces config

Here's a sample of how to add your listener

<faces-config>
 <lifecycle>	 
  <phase-listener>org.foochal.web.controller.jsf.JsfPhaseListener</phase-listener></lifecycle>
</faces-config>

Personal tools