Tuesday, September 07, 2010

Handling HTTP 404 - Page Not Found

If you develop web applications, you are most likely familiar with Java Servlets and Java Server Pages (JSP). JSPs can be accessed by a path that directly relates to their relative location to the web app's content root directory. Servlets however are typically accessed via path that match URL patterns defined for each servlet in the servlet mapping element of the deployment descriptor (web.xml).

What happens if a user types in a URL that will reach your web application, but does not map to to any of your servlets nor JSPs? Most likely this occurrence will be handler by the servlet container itself by sending HTTP 404 code back to the user's browser. A 404 page will be displayed. 404 is a HTTP response status code that indicates that a resource could not be found but may be available again in the future. Most of the servlet containers do not serve user-friendly 404 pages.

You are better off handling 404 by the web application itself. The content of the 404 page can be then customized to suit your web application's needs. You could take a funny approach or present something more helpful, e.g. a sitemap.

Example from YOU & I tee - couple t-shirts:
404 Page Not Found

So how do we do this?

Step 1 - Create error page description

Add an error-page element to your web applications deployment descriptor. Open web.xml file and add a section like the following:

<error-page>
<error-code>404</error-code>
<location>/error404.jsp</location>
</error-page>

Step 2 - Create error JSP

At the location as specified in step 1 create a new JSP file that will serve the content you desire. And that's it really.

Handling exceptions

In a similar fashion you can handle uncaught exceptions that would otherwise end up in the user's browser. For example:

<error-page>
<exception-type>java.lang.RuntimeException</exception-type>
<location>/exception.jsp</location>
</error-page>

No comments:


Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.