Using a PhaseListener
There’s an event type we haven’t
talked about so far, namely the
javax.faces.event.PhaseEvent. This is an event
that fires before and after each request processing lifecycle phase,
invoking all javax.faces.event.PhaseListener
instances registered with the
javax.faces.lifecycle.Lifecycle infrastructure
object responsible for coordinating the request processing.
A very simple application probably doesn’t have any
use for this event, but it can come in handy in some scenarios.
For
instance, say that your application relies on an external resource
(such as a database). Instead of dealing with the (hopefully rare)
situation that the database is unavailable in all component event
handlers, you can use a PhaseListener that checks
the resource status and navigates to an error page if
it’s not available. Here’s an
outline for such a listener:
package com.mycompany.event; import javax.faces.application.NavigationHandler; import javax.faces.context.FacesContext; import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; public class CheckResourceListener implements PhaseListener { public PhaseId getPhaseId( ) { return PhaseId.RESTORE_VIEW; } public void beforePhase(PhaseEvent event) { } public void afterPhase(PhaseEvent event) { FacesContext context = event.getFacesContext( ); if (!isEverythingOkay(context)) { NavigationHandler nh = context.getApplication( ).getNavigationHandler( ); nh.handleNavigation(context, null, ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access