How to configure a single generic error page in web.xml

In this post, we will see how to configure single generic error page in web.xml for all error codes without any code repetition effort. In the end, I will also give you the code for handling common error codes if you are working with Servlet 2.5 and below.

Every web application that you code in Java has a deployment descriptor file (web.xml) that tells the server about all different resources of your project. The deployment descriptor is an XML file and every XML file stores its schema in a corresponding XSD (XML Schema Definition) file.

How can we specify an error page using web.xml file?

You can either configure your web.xml to handle specific error codes or specific Java exceptions, or both. Here’s the syntax of specifying error pages using error codes in web.xml:

And if you want to do the same with an exception type, simply replace <error-code> with <exception-type>. Here’s the syntax of doing it.

In the first case, whenever the server encounters an error code that is handled in the web.xml, it will redirect to the corresponding error page. But the server also handles exceptions that are generated by the container while executing the servlet.

The second syntax can be used to tell the server to show a particular error page when the servlet code generates a specific exception.

How can we specify a single generic error page in web.xml file?

If you use the above given syntax, you can use multiple such <error-page> tags to configure different error pages for each type of error that your application may generate. However, there was no specification to handle multiple errors on a single, generic error page in Servlets / JSP.

Fortunately, with Servlet 3.0, the and tags were made optional in the XSD file of web.xml. The syntax of configuring a single generic error page in web.xml is given below:

The above code will tell the server that whatever the error code or exception type, it should redirect it to a single error page given in the <location> tag.

Unfortunately, if you are using any version below Servlet 3.0, you will have to repeat the tag with same location for each of your error codes and exception types. To avoid this repetitive coding effort, you must upgrade to Servlet 3.0.

The code for setting up most common error codes with a single generic error page in web.xml using Servlet 2.5 and below is as follows:

This same code can be used for JSP as well, since a JSP is translated into a servlet class automatically by the web server.

Leave a Reply