My previous entry dove under the covers for JSF 2.0 and examined composite component metadata.  This one is far less esoteric and shows how to handle the ViewExpiredException using a new JSF feature, the ExceptionHandler, contributed by Pete Muir a JSF Expert Group representative from JBoss.

JSF throws a ViewExpiredException when a postback is made to a view and, for whatever reason, that view cannot be restored. Usually this is due to a session timeout, but a custom state management solution could also cause this exception to be thrown.  The default behavior in JSF2 is to show the Facelets error page saying View Expired.  The default page is illustrated at right.

The default ViewExpiredException error page

One way to fix this is to declare an <error-page> element in your web.xml, as shown here.

  1.     <error-page>
  2.         <exception-type>javax.faces.application.ViewExpiredException</exception-type>
  3.         <location>/faces/viewExpired.xhtml</location>
  4.     </error-page>

This works well enough.  You can even put JSF components on the error page if you put the proper Faces Servlet mapping in the <location> element, as shown above.  If you want to do some application level manipulation in response to the exception, you'll want something different, however.  In this case, a custom ExceptionHandler is just the trick.  I cover this in much more detial in my upcoming book, JavaServer Faces 2.0: The Complete Reference, and the example shown in this blog entry is neatly integrated into the chapter 10 sample app.  Consider this blog entry an appetizer.  So delete that old web.xml (it's not needed if you have JSF2 and Servlet 3, which you get in Glassfish V3) and let's go.

First, we need to install a custom ExceptionHandler. This is done using the tried and true JSF decorator pattern.  In this case, we place the following into the faces-config.xml. There's no annotation for this because it's relatively uncommon, and we expect advanced users to use the feature.  Therefore, the EG tradeoff was to not add yet another "scan for this annotation" clause to the spec.

  1.   <factory>
  2.       <exception-handler-factory>com.sun.faces.ViewExpiredExceptionExceptionHandlerFactory</exception-handler-factory>
  3.   </factory>

Here's the code for the class.

  1. package com.sun.faces;
  3. import javax.faces.context.ExceptionHandler;
  4. import javax.faces.context.ExceptionHandlerFactory;
  6. public class ViewExpiredExceptionExceptionHandlerFactory extends ExceptionHandlerFactory {
  8.     private ExceptionHandlerFactory parent;
  10.     public ViewExpiredExceptionExceptionHandlerFactory(ExceptionHandlerFactory parent) {
  11.         this.parent = parent;
  12.     }
  14.     @Override
  15.     public ExceptionHandler getExceptionHandler() {
  16.         ExceptionHandler result = parent.getExceptionHandler();
  17.         result = new ViewExpiredExceptionExceptionHandler(result);
  19.         return result;
  20.     }
  23. }

The interesting things happen on lines 15 - 20.  This method is called once per request must return a new ExceptionHandler instance each time it's called.  I know the method name should be createExceptionHandler, but we stuck with "get" for consistence with other JSF methods.  On line 17, we call the real ExceptionHandlerFactory and ask it to create the instance, which we then wrap in our custom ViewExpiredExceptionExceptionHandlerFactory class.  This is where the real interesting stuff happens.

  1. package com.sun.faces;
  3. import java.util.Iterator;
  4. import java.util.Map;
  5. import javax.faces.FacesException;
  6. import javax.faces.application.NavigationHandler;
  7. import javax.faces.application.ViewExpiredException;
  8. import javax.faces.component.UIViewRoot;
  9. import javax.faces.context.ExceptionHandler;
  10. import javax.faces.context.ExceptionHandlerWrapper;
  11. import javax.faces.context.FacesContext;
  12. import javax.faces.event.ExceptionQueuedEvent;
  13. import javax.faces.event.ExceptionQueuedEventContext;
  15. public class ViewExpiredExceptionExceptionHandler extends ExceptionHandlerWrapper {
  17.     private ExceptionHandler wrapped;
  19.     public ViewExpiredExceptionExceptionHandler(ExceptionHandler wrapped) {
  20.         this.wrapped = wrapped;
  21.     }
  23.     @Override
  24.     public ExceptionHandler getWrapped() {
  25.         return this.wrapped;
  26.     }
  28.     @Override
  29.     public void handle() throws FacesException {
  30.         for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
  31.             ExceptionQueuedEvent event =;
  32.             ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
  33.             Throwable t = context.getException();
  34.             if (t instanceof ViewExpiredException) {
  35.                 ViewExpiredException vee = (ViewExpiredException) t;
  36.                 FacesContext fc = FacesContext.getCurrentInstance();
  37.                 Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
  38.                 NavigationHandler nav =
  39.                         fc.getApplication().getNavigationHandler();
  40.                 try {
  41.                     // Push some useful stuff to the request scope for
  42.                     // use in the page
  43.                     requestMap.put("currentViewId", vee.getViewId());
  45.                     nav.handleNavigation(fc, null, "viewExpired");
  46.                     fc.renderResponse();
  48.                 } finally {
  49.                     i.remove();
  50.                 }
  51.             }
  52.         }
  53.         // At this point, the queue will not contain any ViewExpiredEvents.
  54.         // Therefore, let the parent handle them.
  55.         getWrapped().handle();
  57.     }
  58. }

On line 15, you see we take advantage of the javax.faces.context.ExceptionHandlerWrapper convenience class.  JSF has lots of these wrapper classes and when you use them, you need only override the getWrapped() method to return the instance of the class you're wrapping, which is often simply passed to the constructor, as shown on lines 19 - 21.  Once you override getWrapped(), you need only override those methods you're interested in.  In this case, we want to override only handle(), which we do on lines 29 - 57.

We iterate over the unhandler exceptions using the iterator returned from getUnhandledExceptionQueuedEvents().iterator(), as shown on line 30.  The ExeceptionQueuedEvent is a SystemEvent (also described in detail in my book) from which we can get the actual ViewExpiredException, which I do on line 35.  I know I'm going to be ultimately showing a JSF page so I want to extract some information from the exception and place it in request scope, so I can access it via EL in the page.  I do this on line 37.

On lines 45 and 46, I leverage the JSF implicit navigation system and cause the server to navigate to the "viewExpired" page.  This assumes, of course, that there is a viewExpired.xhtml page out there.  2015-08-19: This also assumes that the exception we are handling is not happening during the Render Response phase.  If the exception is during the Render Response phase, it is not possible to use the NavigationHandler and you need to find another approach to convey the desired information. Naturally, you could parameterize this howevere you like, context-param, annotation, whatever.  Line 46 causes the intervening lifecycle phases to be skipped.

Note that we have a try-finally block here, and in the finally block, on line 49, we call remove() on the iterator.  This is an important part of the ExceptionHandler usage contract.  If you handle an exception, you have to remove it from the list of unhandled exceptions.  That way, we know it's safe to call getWrapped().handle() on line 55.

Finally, let's see my cheesy viewExpired.xhtml page in action, shown at left.

The customized ViewExpiredException error page

This page is not much more visually appealing than the default one, but that's not JSF's fault!  The one in the JSF2 book will look nicer. Here's the source for this cheesy one.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
  2.      xmlns:h=""
  3.      xmlns:f="">
  4. <h:head>
  5.   <title>Nice View Expired Page</title>
  6. </h:head>
  7. <h:body>
  8. <h:form>
  10.     <p>To protect your security, we have taken the liberty of logging you
  11.     out. Those who sacrifice liberty for security deserve to have
  12.     their views expired.</p>
  14.     <p>You were on page #{currentViewId}.  Maybe that's useful.</p>
  16.   </h:form>
  17. </h:body>
  18. </html>

Note that we show the data from the exception on line 15.

This entry showed you how to programmatically intercept the ViewExpiredException and do something nice with it.  If you have any other state that you can show in the page, it's easy to include it in the Facelets view.

Technorati Tags: edburns