JSF Interceptor

I want to know if there is an interceptor in JSF (as we use in Spring), and how to implement this?

+8
jsf jsf-2 interceptor
source share
1 answer

For this you can implement PhaseListener . You can program them to listen on a specific JSF phase , which you specify in the overridden getPhaseId() . You can intercept events before and after the beforePhase() and afterPhase() phases.

The following example listens for the render response phase:

 public class RequestInterceptor implements PhaseListener { @Override public PhaseId getPhaseId() { return PhaseId.RENDER_RESPONSE; } @Override public void beforePhase(PhaseEvent event) { // Do your job here which should run before the render response phase. } @Override public void afterPhase(PhaseEvent event) { // Do your job here which should run after the render response phase. } } 

To run it, you need to register it as <phase-listener> in the <life-cycle> section of faces-config.xml . You can have multiple <phase-listener> s.

 <lifecycle> <phase-listener>com.example.RequestInterceptor</phase-listener> </lifecycle> 

You can specify PhaseId.ANY_PHASE in getPhaseId() so that the phase listener works on each individual JSF phase (note that not all of them will always be executed, depending on the type of request). If necessary, you can get the identifier of the current phase in the methods before and after the PhaseEvent#getPhaseId() phase.

 public class PhaseDebugger implements PhaseListener { @Override public PhaseId getPhaseId() { return PhaseId.ANY_PHASE; } @Override public void beforePhase(PhaseEvent event) { System.out.println("Before phase " + event.getPhaseId()); } @Override public void afterPhase(PhaseEvent event) { System.out.println("After phase " + event.getPhaseId()); } } 

Alternatively, Filter should work equally well if you want a more global hook (and therefore you are not interested in JSF requests / responses, and you don't need anything from FacesContext ).

 @WebFilter("/*") public class RequestInterceptor implements Filter { @Override public void init(FilterConfig config) { // Initialize global variables if necessary. } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { // Do your job here which should run before the request processing. chain.doFilter(request, response); // Do your job here which should run after the request processing. } @Override public void destroy() { // Cleanup global variables if necessary. } } 
+10
source share

All Articles