Saturday, February 21, 2009

Catch All exception page for a JSF web application

If your application wants to display a generic error page if an internal exception occurs in your web application then all you have to do is register an action listener in your faces config, under the application as follows


Once you have configured your faces config with the action listener you create your java class called GlobalActionListener

import com.sun.faces.application.ActionListenerImpl;
import javax.faces.application.Application;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.servlet.http.HttpSession;

public class GlobalActionListener extends ActionListenerImpl implements ActionListener{
public GlobalActionListener() {
public void processAction(ActionEvent event){
}catch(Throwable exception){
//This part of the code is reached if any of your pages throw an exception and if it is not handled
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
// goto this error page
NavigationHandler nhandler = app.getNavigationHandler();
nhandler.handleNavigation(fc, null, "exceptionNavigation");
// invalidate the session
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpSession session = (HttpSession)ectx.getSession(false);

Our GlobalActionListener implements the interface ActionListener and implements processAction method. It also extends the default Implementation from sun's class ActionListenerImpl. All that we have to do is call the base class's process Action and if an exception is throw catch that and redirect it to an exception page. In addition to redirecting to the exception page we also invalidate the http session.

The NavigationHandler class navigates to the exception page defined in faces config.

No comments: