Monday, January 9, 2012

<error-page> catch-all feature in servlet 3.0

 

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.
There is a example here. We want to catch ArithmeticException and display /arithmeticError.jsp instead of default /errorPage.jsp, in servlet 3.0, this is the DD:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="
http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet>
        <servlet-name>JSTLSample</servlet-name>
        <servlet-class>web.JSTLServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>JSTLSample</servlet-name>
        <url-pattern>/JSTLSample.do</url-pattern>
    </servlet-mapping>
    <error-page>
        <location>/errorPage.jsp</location>
    </error-page>

    <error-page>
        <exception-type>java.lang.ArithmeticException</exception-type>
        <location>/arithmeticError.jsp</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/notFoundError.jsp</location>
    </error-page>
</web-app>

In previous version, DD is like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="
http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet>
        <servlet-name>JSTLSample</servlet-name>
        <servlet-class>web.JSTLServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>JSTLSample</servlet-name>
        <url-pattern>/JSTLSample.do</url-pattern>
    </servlet-mapping>
    <error-page>
       <exception-type>java.lang.Throwable</exception-type>
       <location>/errorPage.jsp</location>
    </error-page>

    <error-page>
        <exception-type>java.lang.ArithmeticException</exception-type>
        <location>/arithmeticError.jsp</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/notFoundError.jsp</location>
    </error-page>
</web-app>

No comments:

Post a Comment