O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

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

9.2. Creating an Exception-Handling Servlet

Problem

You want to create a servlet that generates an error page.

Solution

Create a servlet that displays some information about the error, then map exception types and/or error codes to the servlet in the deployment descriptor.

Discussion

An error-handling servlet has access to several request attributes that it can use to describe the error. The error page also has access to the request and response objects associated with the page that generated the error. For example, the java.lang.Throwable object associated with any exceptions can be accessed with the following code:

Throwable throwable = (Throwable)
   request.getAttribute("javax.servlet.error.exception");

You can access the server response code with this code:

String status_code = ((Integer)
   request.getAttribute("javax.servlet.error.status_code")).toString( );

Table 9-1 shows the request attributes that an error-handling servlet has access to.

Table 9-1. Request attributes available to servlet error pages

Request attribute

Java type

javax.servlet.error.status_code
java.lang.Integer
javax.servlet.error.exception_type
java.lang.Class
javax.servlet.error.message
java.lang.String
javax.servlet.error.exception
java.lang.Throwable
javax.servlet.error.request_uri
java.lang.String
javax.servlet.error.servlet_name
java.lang.String

Example 9-2 shows the ErrorGen servlet. The web container invokes this servlet when another servlet or JSP throws an unhandled Throwable, according to the ...

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