views:

24

answers:

1

How to make a ErrorController, like the ErrorController in the Zend Framework for PHP, with servlets in java?

Now I have this

<servlet>
        <display-name>ErrorController</display-name>
        <servlet-name>ErrorController</servlet-name>
        <servlet-class>project.controller.ErrorController</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ErrorController</servlet-name>
        <url-pattern>/error</url-pattern>
    </servlet-mapping>

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

Is it possible to have something similar with servlets?

+1  A: 

I am not sure about Zend, but in Java/Servlet you can define error pages for specific error codes (definition goes into WEB-INF/web.xml):

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

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

The location is not necessarily required to be jsp and can then be chewed by a filter which would take user to a relevant controller.

mindas
You can likewise assign an error page to a particular Exception class. To assign one to catch all possible Throwable, use `<exception-type>java.lang.Throwable</exception-type>` instead.
Sean Owen
@Sean this is of course a possibility, but I don't really imagine why would anybody want to deal with exception handling via web.xml. Is it not better to handle the exception in a generic dispatcher and tackle it accordingly?
mindas
I tend to agree. One thing to remember is that you ought to handle errors from JSPs, which may be outside whatever dispatcher framework you establish. You could handle that with a `Filter` though. This mechanism is older, if I recall correctly, from the heady days of J2EE 1.1 or so when everything was going to be XML and declarative! You can use either or both.
Sean Owen