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 the URL mapping rules the Container uses to choose the “winner” when a client makes a request for a resource, because ALL filters that match will be placed in the chain!! Filters with matching URL patterns are placed in the chain in the order in which they are declared in the DD.

2) Once all filters with matching URLs are placed in the chain, the Container does the same thing with filters that have a matching <servlet-name> in the DD.

image with no caption
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset