Chapter 9. Handling Exceptions in Web Applications


Web applications can sometimes show a number of errors that you don’t want users to see. If a user who expects to be served an information-rich page is instead greeted with an ugly and incomprehensible announcement of an “HTTP Status 500” in her web browser, you can bet this visit to the site will be her last! All web sites handle unexpected HTTP status codes (such as the “404 Not Found” or “403 Forbidden”) with a friendly and informative error message, but you’ll want to hide these messages from your users. Tools to handle both Java runtime exceptions and these unanticipated HTTP status codes are available to developers, and the recipes in this chapter show you how to use them effectively.

9.1. Declaring Exception Handlers in web.xml


You want to display certain servlets or JSPs when a web component throws a Java exception or generates unexpected server response codes.


Use the error-page element in web.xml to specify the invocation of servlets or JSPs in response to certain exceptions or HTTP status codes.


A Java web developer should handle these types of unexpected occurrences within his web application:

  • The "404 Not Found” server response code, which indicates that the user has made a mistake when typing in the URL, or requested a page that no longer exists.

  • The "500 Internal Server Error” that can be raised by a servlet when it calls sendError(500) on the HttpServletResponse object.

  • Runtime ...

Get Java Servlet & JSP Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.