2 Minutes To Code (β Version)

Java Servlets - 2 minute tutorial

How to deploy your filters

Let's see how to configure filters in the deployment descriptor.

The filter mapping are identical to servlet mapping in deployment descriptor explained in this tutorial on Apache Tomcat.

In the example below, all urls are mapped to the filter class com.tf.LogResponseTime.java.
<web-app>

    <filter>
        <filter-name>ResponseTime</filter-name>
        <filter-class>com.tf.LogResponseTime</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>ResponseTime</filter-name>
        <url-pattern>*</url-pattern>
    </filter-mapping>
</web-app>

When defining filters, you can also some initial parameters to it using <init-param> elements as shown below. These can be retrieved by in the filter class using the api String FilterConfig.getInitParameter(String).
    <filter>
        <filter-name>ResponseTime</filter-name>
        <filter-class>com.tf.LogResponseTime</filter-class>
        <init-param>
            <param-name>timeUnits</param-name>
            <param-value>millisec</param-value>
        </init-param>
    </filter>

To map all resources under section /secure use the configuration as shown below.
    <filter-mapping>
        <filter-name>ResponseTime</filter-name>
        <url-pattern>/secure/*</url-pattern>
    </filter-mapping>

To map a specific url to a filter, use the config as shown below.
    <filter-mapping>
        <filter-name>ResponseTime</filter-name>
        <url-pattern>/secure/transaction.do</url-pattern>
    </filter-mapping>

To map url for resources with a specific extension (say ".do" ) to a filter, use the config as shown below.
    <filter-mapping>
        <filter-name>ResponseTime</filter-name>
        <url-pattern>/secure/*.do</url-pattern>
    </filter-mapping>