You are on page 1of 2

jsf 2 - Interceptor in JSF https://stackoverflow.

com/questions/8709107/interceptor-in-jsf

jsf 2 - Interceptor in JSF

You could implement a PhaseListener for this. You could program them to listen on a specific JSF phase which you specify in the overridden getPhaseId() method. You can intercept on the before and after
phase events by beforePhase() and afterPhase() methods.

The below example listens on 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 get it to run, you need to register it as a <phase-listener> in the <life-cycle> section of the faces-config.xml file. You can have multiple <phase-listener>s.

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

You can specify PhaseId.ANY_PHASE in getPhaseId() to let the phase listener run on every single JSF phase (note that not necessarily all of them will always be executed, that depends on the request type).
You can if necessary get the current phase ID in the before and after phase methods by PhaseEvent#getPhaseId().

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, a Filter should work equally good if you want a more global hook (and thus you're not exactly interested in JSF requests/responses and you do not need anything from the FacesContext).

1 of 2 15/10/19, 10:48 AM
jsf 2 - Interceptor in JSF https://stackoverflow.com/questions/8709107/interceptor-in-jsf

@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.
}

2 of 2 15/10/19, 10:48 AM

You might also like