Using a servlet filter for 404 error-page

Posted December 20, 2006 by

The upcoming Wicket 1.3 and 2.0 versions intercept their requests using a servlet filter to provide more flexible resource mapping and nicer URLs. Your Wicket pages no longer need to live at foo.com/app/PageName and can instead be rooted properly at foo.com/PageName.

This is now working well. I did, however, come up against a small issue, which is how you serve custom error pages for your 404 or 500 responses. It’s nice to render these like any other pages, so you can use your branding and whatnot. This used to work fine with Wicket as a servlet, but switching to a filter broke things. I did some digging around before reading the servlet spec in more detail and finally realising you need a Servlet 2.4 spec container and web.xml config file, with some <dispatcher> elements in your filter mapping.

The following does the trick:

<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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
<filter>
  <filter-name>WicketFilter</filter-name>
  <filter-class>wicket.protocol.http.WicketFilter</filter-class>
  <init-param>
    <param-name>applicationClassName</param-name>
    <param-value>com.foo.TheApplication</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>WicketFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>ERROR</dispatcher>
</filter-mapping>
<error-page>
  <error-code>404</error-code>
  <location>/NotFound</location>
</error-page>
</web-app>

Post Details

6 Opinions have been expressed on “Using a servlet filter for 404 error-page”. What is your opinion?

  1. eric vantillard commented:

    Very usefull especially with frameworks like WebWorks.

    Thanks !

  2. Allen Mayers commented:

    This would be good info, except for the

    “The following does the trick:
    sh: /usr/bin/states: No such file or directory ”

    bit. Could you post the dispatcher element syntax ?

  3. Allen Mayers commented:

    Presumably one adds something like :

    ERROR
    FORWARD
    INCLUDE
    REQUEST

    in the filter, but what exactly do these map to or do ?

  4. Alastair commented:

    Sorry, recently migrated this blog to another hosting provider. I’ve now sorted out the syntax highlighting. Apologies for the interruption to normal service.

  5. massa commented:

    Thanks a lot for this very, very useful trick :-)

  6. Anonymous commented:

    Thanks for the useful tip

Leave a Reply