Using a JSP Error Page for All Runtime Errors
Even if an
application is developed with different
types of components, it should deal with runtime errors in a
consistent way. Recall from Chapter 7, how the
page directive can specify a JSP page to be used
when code in the JSP page
throws an exception. The error page gets
access to the exception through an implicit variable named
exception, and can display a user-friendly message
as well as log details about the problem. The way the error page is
invoked and how the implicit variable gets its value can easily be
mimicked by a
servlet. Example 14.4 shows how to do this in the controller servlet
used in previous examples in this chapter.
Example 14-4. Invoking a JSP Error Page from a Servlet
public void doPost(HttpServletRequest request,
HttpServletResponse response) {
...
try {
action.perform(this, request, response);
}
catch (Throwable t) {
request.setAttribute("javax.servlet.jsp.jspException", t);
RequestDispatcher rd =
getServletContext( ).getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
}The servlet calls the action’s perform( )
method within a try block. If any type of
exception occurs while executing an action, the servlet catches it,
sets the javax.servlet.jsp.jspException request
attribute to the exception object, and forwards the request to the
error JSP page. The javax.servlet.jsp.jspException attribute name is reserved for the exception object in the JSP specification, so the JSP container picks up the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access