Using a servlet filter for 404 error-page

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>

6 thoughts on “Using a servlet filter for 404 error-page”