Mapping Filters to URLs
The filter-mapping element maps a URL pattern or servlet name to an instance of a filter. The filter-mapping always contains a filter-name element and a url-pattern element.
The filter-name element must match a filter-name defined in a filter element elsewhere in the web.xml file. Since a servlet container may have multiple instances of the same servlet running, the servlet container uses the filter-name to associate a mapping with a filter.
A filter-mapping maps a filter to a URL pattern. Therefore, each filter-mapping contains a single url-pattern element. Notice that the url-pattern for a filter need not exactly match the url-pattern in any particular servlet-mapping.
For example, the web.xml fragment below maps the URL /status/compressed/* to a filter named compressResponse. If the servlet is defined in the examples context of a servlet container at http://example.com/, this element tells the container that the compressResponse filter will process any requests beginning with http://example.com/example/status/compressed/.
 
<filter-mapping>
<filter-name>compressResponse</filter-name>
<url-pattern>/status/compressed/*</url-pattern>
</filter-mapping>
A single filter instance can be mapped to any number of URL patterns. The fragment below maps the same filter to two different servlets.
 
<filter-mapping>
<filter-name>compressResponse</filter-name>
<url-pattern>/status/compressed/*</url-pattern>
</filter-mapping>
 
<filter-mapping>
<filter-name>compressResponse</filter-name>
<url-pattern>/photos/compressed/*</url-pattern>
</filter-mapping>
Any number of instances within a context may be mapped to the same URL pattern. Filters are added to the filter chain in the order in which the filter-mapping appears in the web.xml file. For example, the web.xml fragment below defines two filters for servlets located at /status/compressed/*:
 
<filter>
<filter-name>Uncompress</filter-name>
<filter-class>compressFilters.createUncompress</filter-class>
</filter>
 
<filter>
<filter-name>Authenticate</filter-name>
<filter-class>authentication.createAuthenticate</filter-class>
</filter>
 
<filter-mapping>
<filter-name>Uncompress</filter-name>
<url-pattern>/status/compressed/*</url-pattern>
</filter-mapping>
 
<filter-mapping>
<filter-name>Authenticate</filter-name>
<url-pattern>/status/compressed/*</url-pattern>
</filter-mapping>
Both Uncompress and Authenticate appear on the filter chain for servlets located at /status/compressed/*. The Uncompress filter precedes the Authenticate filter in the chain because the Uncompress filter appears before the Authenticate filter in the web.xml file.