O'Reilly logo

JavaServer Faces by Hans Bergsten

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required