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.4. Changing the Order in Which Filters are Applied to Servlets

Problem

You want to change the order in which filters are applied to web components.

Solution

Change the order of filter-mapping elements in the deployment descriptor.

Discussion

The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet. Example 19-5 reverses the order of the filter-mapping elements that map two filters to the servlet named requestheaders, compared with Recipe 19.3. The LogFilter is thus applied to the servlet before the AuthenFilter. Any requests for the servlet pass through a chain: LogFilter AuthenFilter requestheaders servlet.

Example 19-5. Reversing the order of filter-mapping elements

<!-- LogFilter applies to the requestheaders servlet 
before AuthenFilter -->

<filter-mapping>
    <filter-name>LogFilter</filter-name>
    <servlet-name>requestheaders</servlet-name>
</filter-mapping>

<filter-mapping>
    <filter-name>AuthenFilter</filter-name>
    <servlet-name>requestheaders</servlet-name>
</filter-mapping>

See Also

Recipe 7.9 on using a filter to read request parameter values; Recipe 11.11 on using a filter to monitor session attributes; Recipe 18.3 on using a filter to alter then forward the request; Recipe 19.1-Recipe 19.3 on mapping filters to web components; Recipe 19.5 on configuring filter init parameters; Recipe 19.6 on blocking requests; Recipe 19.7 on filtering the HttpServletResponse; Recipe 19.8 on using filters with RequestDispatchers ...

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