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

Chapter 9. Handling Exceptions in Web Applications

Introduction

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

Problem

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

Solution

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.

Discussion

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 ...

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