How do I trap a 404 error inside my servlet if my servlet does a RequestDispatcher to a non-existent page ?

Alessandro A. Garbagnati

[See How can I write an "error page" -- that is, a serv... for the canonical FAQ on error pages. -A]

In Tomcat, like in all the fully compliant servlet containers, you have the equivalent of the 'ErrorDocument' using the web application descriptor (web.xml).
This is useful because you can handle either error codes (like the 404) or even exception.

This is the extract of the web.xml DTD:

<!-- The error-page element contains a mapping between an error code or exception type to the path of a resource in the web application -->
<!ELEMENT error-page ((error-code | exception-type), location)>

<!-- The error-code contains an HTTP error code, ex: 404 -->
<!ELEMENT error-code (#PCDATA)> <!--

The exception type contains a fully qualified class name of a Java exception type. -->
<!ELEMENT exception-type (#PCDATA)>

<!-- The location element contains the location of the resource in the web application -->
<!ELEMENT location (#PCDATA)>