How can I implement a PhaseListener which runs at end of the JSF lifecycle?
A JSF phase listener is a class that implements javax. faces. event. PhaseListener and is registered in the web application's faces-config. xml file.
An interface implemented by objects that wish to be notified at the beginning and ending of processing for each standard phase of the request processing lifecycle. Method Summary.
You need to implement the PhaseListener interface and hook on beforePhase() of the PhaseId_RENDER_RESPONSE. The render response is the last phase of the JSF lifecycle.
public class MyPhaseListener implements PhaseListener { @Override public PhaseId getPhaseId() { return PhaseId.RENDER_RESPONSE; } @Override public void beforePhase(PhaseEvent event) { // Do your job here which should run right before the RENDER_RESPONSE. } @Override public void afterPhase(PhaseEvent event) { // Do your job here which should run right after the RENDER_RESPONSE. } } To get it to run, register it as follows in faces-config.xml:
<lifecycle> <phase-listener>com.example.MyPhaseListener</phase-listener> </lifecycle> Update the above phase listener is indeed applicaiton-wide. To have a phase listener for a specific view, use the beforePhase and/or afterPhase attributes of the <f:view>.
E.g.
<f:view beforePhase="#{bean.beforePhase}"> ... </f:view> with
public void beforePhase(PhaseEvent event) { if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) { // Do here your job which should run right before the RENDER_RESPONSE. } } A more JSF 2.0 way is by the way using the <f:event type="preRenderView">:
<f:event type="preRenderView" listener="#{bean.preRenderView}" /> with
public void preRenderView() { // Do here your job which should run right before the RENDER_RESPONSE. }
In jsf 2 you can use <f:phaseListener type="my.MyPhaseListener"> to hook MyPhaseListener for some facelet. MyPhaseListener should implement PhaseListener and override
afterPhase - with code to be run after end of phase beforePhase - with code to be run before phase started getPhaseId - PhaseId enum specifying name of phase for which the listener to be invoked (PhaseId.RENDER_RESPONSE as last phase of lifecycle)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With