News Flash: As of version 2.4, filters can be applied to request dispatchers

Think about it. It’s great that filters can be applied to requests that come directly from the client. But what about resources requested from a forward or include, request dispatch, and/or the error handler? Servlet spec 2.4 to the rescue.

Declaring a filter mapping for request-dispatched web resources

<filter-mapping>
  <filter-name>MonitorFilter</filter-name>
  <url-pattern>*.do</url-pattern>
  <dispatcher>REQUEST</dispatcher>

        - and / or -

  <dispatcher>INCLUDE</dispatcher>

        - and / or -

  <dispatcher>FORWARD</dispatcher>

        - and / or -

  <dispatcher>ERROR</dispatcher>
</filter-mapping>

Declaration Rules

  • The <filter-name> is mandatory.

  • Either the <url-pattern> or <servlet-name> element is mandatory.

  • You can have from 0 to 4 <dispatcher> elements.

  • A REQUEST value activates the filter for client requests. If no <dispatcher> element is present, REQUEST is the default.

  • An INCLUDE value activates the filter for request dispatching from an include() call.

  • A FORWARD value activates the filter for request dispatching from a forward() call.

  • An ERROR value activates the filter for resources called by the error handler.

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.