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.
Sharpen your pencil
Based on the following DD fragment, write down the sequence in which the filters will be executed for each request path. Assume Filter1 through Filter5 have been properly declared, and that the servlet names are the same as their mappings. (Answers are at the end of this chapter.)
<filter-mapping> <filter-name>Filter1</filter-name> <url-pattern>/Recipes/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Filter2</filter-name> <servlet-name>/Recipes/HopsList.do</servlet-name> </filter-mapping> <filter-mapping> <filter-name>Filter3</filter-name> <url-pattern>/Recipes/Add/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Filter4</filter-name> <servlet-name>/Recipes/Modify/ModRecipes.do</servlet-name> </filter-mapping> <filter-mapping> <filter-name>Filter5</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Request path | Filter Sequence |
---|---|
| Filters: |
| Filters: |
| Filters: |
| Filters: |
| Filters: |