2 Minutes To Code (β Version)

Apache Tomcat - 2 minute tutorial

How to configure filters in deployment descriptor (web.xml)

Servlet specification supports http filters which are explained in the tutorial on java servlets .

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

The filter mapping are identical to servlet mapping in deployment descriptor explained earlier. 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>
        
            <param-name>timeUnits</param-name>
            <param-value>millisec</param-value>
        
    </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>