O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

19.3. Mapping More Than One Filter to a Servlet

Problem

You want requests for a servlet or JSP to pass through more than one filter.

Solution

Map each filter to the servlet or JSP using filter-mapping elements in the deployment descriptor. The filters are applied to the servlet in the order they appear in the deployment descriptor.

Discussion

Your web application may define several different filters with a specific purpose. For instance, one filter might log messages, while another filter authenticates users. It is straightforward to create a filter chain that applies each filter in a specified order to a servlet. You use the filter-mapping element to map each filter to the target servlet (or JSP). The web container then applies the filters to the target in the order that the filter-mapping elements are defined in the deployment descriptor.

Example 19-4 configures two filters: AuthenFilter and LogFilter. The filter-mapping elements for these filters then map the servlet name requestheaders to each of these filters. The order of the filter-mapping elements in Example 19-4 specifies that the authentication filter (AuthenFilter) must be applied to the servlet named requestheaders first, followed by the LogFilter.

To map a filter to a servlet name, the servlet has to be registered in web.xml. Example 19-4 registers the requestheaders servlet beneath the filter and filter-mapping elements.

Example 19-4. Mapping more than one filter to a servlet

<!-- top of web.xml deployment descriptor --> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required