Using a Common JSP Error Page

Before we end the exploration of the combination of JSP and servlets, I’d like to give you one more useful tip, namely how to use a JSP error page that displays a user-friendly error page for all runtime errors, no matter if they originate in a JSP page, a servlet, or a filter.

In Chapter 9, I showed you how to use the page directive’s errorPage attribute to specify a JSP page that is invoked in case an exception is thrown while processing the page. I also mentioned that an alternative is to declare an error page in the deployment descriptor (the WEB-INF/web.xml file). It’s then used for exceptions thrown by a servlet, a filter, or a JSP page that doesn’t declare an error page:

<error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/errorpage.jsp</location>
</error-page>

To recap, the <exception-type> element contains the fully qualified name of the type of exception you want to handle with the servlet, JSP page, or static page specified by the <location> element. The <location> value must be a context-relative path (starting with a slash). You can use multiple <error-page> elements to use different pages for different exceptions, and the container picks the one with the <exception-type> element that most closely matches the type of the exception thrown.

You can also define a custom handler for response status codes other than 200 (i.e., status codes that signal some kind of problem):

<error-page> <error-code>404</error-code> <location>/notfound.jsp</location> ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.