JSF Phase Listener
From Foochal
Contents |
[edit]
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:
- RESTORE_VIEW
- RENDER_RESPONSE
[edit]
Clicking a button or a link on a JSF page
The following phases are invoked when this request goes to the JSF controller:
- RESTORE_VIEW
- APPLY_REQUEST_VALUES
- PROCESS_VALIDATIONS
- UPDATE_MODEL_VALUES
- INVOKE_APPLICATION
- RENDER_RESPONSE
[edit]
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;
}
}
[edit]
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>

