TOTD #136: Default Error Page using Servlets 3.0 - Improved productivity using Java EE 6

Servlets 2.x allowed to create a mapping between an HTTP error code or an exception type to the path of a resource in the Web application. This is achieved by specifying an "error-page" element in the "web.xml". The element definition looks like:

So any HTTP error code or an exception thrown within the application can be mapped to a resource bundled with the application. Here is a sample:

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

Adding the above fragment in "web.xml" of an application will display "error-404.jsp" page to the client if a non-existing resource is accessed. This mapping can be easily done for other HTTP status codes as well by adding other <error-page> elements.

Similarly, <exception-type> element can be used to map an exception to a resource in the web application. This allows fine-grained mapping of errors from your web application to custom pages.

Starting with Servlets 3.0, <error-code> and <exception-type> elements are optional. An <error-page> without any <exception-type> and <error-code> will be considered as the webapp's default error page, and will act as a "catch-all" for any error codes or exception types. It will be an error if a web.xml contains more than one such default error page.

A default error page may be overridden for specific exception types and error codes. For example:

     <error-page>
       <location>/error-default.jsp</location>
     </error-page>

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

Any response with a status code other than 404 will be error-dispatched to /default.jsp, while a 404 response will be error-dispatched to /error-404.jsp.

So if the Servlet code looks like:

@WebServlet(name="HelloServlet", urlPatterns={"/HelloServlet"})
public class HelloServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response) throws IOException {
        String type = (String)request.getParameter("type");

        if (type == null) {
            response.getWriter().print("hello world"); 
            return;
        }

        if (type.equals("helloex")) {   
          throw new HelloException();
        } else if (type.equals("ncdfe")) {
            throw new NoClassDefFoundError();
        } else {
            throw new NullPointerException();
        }
    }
}

And the "web.xml" looks like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <error-page>
       <exception-type>java.lang.NoClassDefFoundError</exception-type>
       <location>/error-ncdfe.jsp</location>
    </error-page>
    <error-page>
       <exception-type>server.HelloException</exception-type>
       <location>/error-helloex.jsp</location>
    </error-page>
    <error-page>
       <error-code>404</error-code>
       <location>/error-404.jsp</location>
    </error-page>
    <error-page>
       <location>/error-default.jsp</location>
    </error-page>
</web-app>

Lets say the directory structure looks like:

WEB-INF/classes/
WEB-INF/classes/server/
WEB-INF/classes/server/HelloException.class
WEB-INF/classes/server/HelloServlet.class
WEB-INF/web.xml
error-404.jsp
error-default.jsp
error-helloex.jsp
error-ncdfe.jsp

and this application is deployed as "DefaultErrorPage.war". Then here is a table of the page that gets displayed when the URL mentioned in the first column is accessed:

URL Response Comment
http://localhost:8080/DefaultErrorPage/HelloServlet "hello world" Expected result
http://localhost:8080/DefaultErrorPage/HelloServlet2 error-404.jsp HTTP 404
http://localhost:8080/DefaultErrorPage/HelloServlet?type=ncdfe error-ncdfe.jsp System exception
http://localhost:8080/DefaultErrorPage/HelloServlet?type=helloex error-helloex.jsp User exception
http://localhost:8080/DefaultErrorPage/HelloServlet?type error-default.jsp Catch-all exception


Try this and other Java EE 6 features in GlassFish Server Open Source Edition 3 or Oracle GlassFish Server today!

The complete source code used in this blog can be downloaded here.

The default setting in Chrome is to show suggestions to navigate to other parts of the website or search with Google. This can be easily disabled by Chrome -> Preferences -> Under the Hood and deselecting "Show suggestions for navigation errors" in Privacy section. This is explained in detail here.

Technorati: totd javaee glassfish v3 servlet default error

Comments:

Is this universal/global

<error-page>
<location>/error-default.jsp</location>
</error-page>

error page definition valid and understandable by all Servlet 3.0 containers?

On Tomcat 7, I still see Tomcat's specific error page.

Posted by Libor Jelínek on April 12, 2012 at 10:06 PM PDT #

Yes, it should work for any Servlet3 compliant container.

Try asking on a Tomcat alias ?

Posted by Arun Gupta on April 13, 2012 at 02:51 AM PDT #

Sorry, what or who is Tomcat alias? Tomcat guys claim that it is not part of Servlet 3.0 standard. But agree that it's very handy and will be probably implemented in Tomcat. But it's still considered as a enhancement only from Tomcat point of view...

Posted by Libor Jelínek on April 13, 2012 at 02:55 AM PDT #

Tomcat debate for interested: https://issues.apache.org/bugzilla/show_bug.cgi?id=52135

Posted by Libor Jelínek on April 13, 2012 at 02:57 AM PDT #

Libor,

Thanks for the link to buzilla. I'm getting clarification from the Servlet specification lead and will get back to you.

Strangely I could not find the appropriate reference in the spec now. Let me get back to you with the clarification.

Posted by Arun Gupta on April 13, 2012 at 03:08 AM PDT #

Arun, the link to download the code returns a 404 error. Is the code still somewhere available?
Regards, Mike

Posted by guest on July 11, 2012 at 08:22 AM PDT #

Fixed the link, this was one of the casualties of blogs.sun.com -> blogs.oracle.com migration.

Posted by Arun Gupta on July 11, 2012 at 02:01 PM PDT #

Is it possible to define it programmatically too?

Thanks

Posted by guest on January 22, 2013 at 05:30 AM PST #

Hi,

Could you please explain as to how this would be different from the fragment below ?

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

Posted by guest on February 12, 2013 at 09:42 PM PST #

The code fragment in the blog will catch any unspecified HTTP error codes as well.

Posted by Arun Gupta on February 15, 2013 at 09:04 AM PST #

Support for this functionality has now been added to Tomcat 7 as well (in 7.0.29).

Posted by guest on April 03, 2013 at 06:29 AM PDT #

Post a Comment:
Comments are closed for this entry.
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today