O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

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

Declaring and ordering filters

When you configure filters in the DD, you’ll usually do three things:

  • Declare your filter

  • Map your filter to the web resources you want to filter

  • Arrange these mappings to create filter invocation sequences

Declaring a filter

<filter>
  <filter-name>BeerRequest</filter-name>
  <filter-class>com.example.web.BeerRequestFilter
        </filter-class>
  <init-param>
    <param-name>LogFileName</param-name>
    <param-value>UserLog.txt</param-value>
  </init-param>
</filter>

Declaring a filter mapping to a URL pattern

<filter-mapping>
  <filter-name>BeerRequest</filter-name>
  <url-pattern>*.do</url-pattern>
</filter-mapping>

Declaring a filter mapping to a servlet name

<filter-mapping>
  <filter-name>BeerRequest</filter-name>
  <servlet-name>AdviceServlet</servlet-name>
</filter-mapping>

Rules for <filter>

  • The <filter-name> is mandatory.

  • The <filter-class> is mandatory.

  • The <init-param> is optional, and you can have many.

Rules for <filter-mapping>

  • The <filter-name> is mandatory and it is used to link to the correct <filter> element.

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

  • The <url-pattern> element defines which web app resources will use this filter.

  • The <servlet-name> element defines which single web app resource will use this filter.

Note

IMPORTANT: The Container’s rules for ordering filters:

When more than one filter is mapped to a given resource, the Container uses the following rules:

1) ALL filters with matching URL patterns are located first. This is NOT the same as ...

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