Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a PhaseListener which runs at end of lifecycle?

How can I implement a PhaseListener which runs at end of the JSF lifecycle?

like image 510
Mahmoud Saleh Avatar asked Dec 05 '11 16:12

Mahmoud Saleh


People also ask

What is JSF PhaseListener?

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.

What is Phase listener?

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.


2 Answers

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. } 
like image 118
BalusC Avatar answered Sep 28 '22 11:09

BalusC


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)
like image 20
Oleksandr Tsurika Avatar answered Sep 28 '22 12:09

Oleksandr Tsurika