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.5. Creating an Error-Handling JSP

Problem

You want to use a JSP as your error page for both servlets and JSPs.

Solution

Create a JSP that displays information about the java.lang.Throwable reported by using the specified request attributes, such as javax.servlet.error.exception. Use the error-page attribute in web.xml to map certain exception types to the JSP.

Discussion

A JSP can display error information in the same manner as the servlet used in Recipe 9.2. Example 9-5 can be used as the error page for both JSPs and servlets. This sample JSP uses the JSTL and the EL to display the thrown exception's various characteristics, such as its fully qualified class name.

Example 9-5. Using a JSP as an error page

<%@page isErrorPage="true" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head><title>Sorry about the error</title></head>
<body>
<h2>Sorry, We Erred Handling Your Request</h2>

<strong>Here is information about the error:</strong> <br><br>

The servlet name associated with throwing the exception: 
<c:out value="${requestScope[\"javax.servlet.error.servlet_name\"]}" />
<br><br>

The type of exception: 
  <c:out value=
    "${requestScope[\"javax.servlet.error.exception\"].class.name}" />
<br><br>

The request URI: 
<c:out value="${requestScope[\"javax.servlet.error.request_uri\"]}" />
<br><br>

The exception message: 
  <c:out value=
    "${requestScope[\"javax.servlet.error.exception\"].message}" />
</body>
</html>

The error page grabs the request Uniform Resource Indicator ...

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