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.5. Configuring Initialization Parameters for a Filter

Problem

You want to make an initialization (init) parameter available to a filter .

Solution

Use the init-param child element of the filter element to declare the initialization parameter and its value. Inside the filter, access the init parameter by calling the FilerConfig object's getInitParameter method.

Discussion

Example 19-6 shows a filter declared in the deployment descriptor. The filter includes an init parameter named log-id.

Example 19-6. A filter declared in the deployment descriptor with an init parameter

<filter>
    <filter-name>LogFilter</filter-name>
    <filter-class>com.jspservletcookbook.LogFilter</filter-class><init-param>
        <param-name>log-id</param-name>
        <param-value>A102003</param-value>
    </init-param>
</filter>

Example 19-7 shows the code you would use inside the filter to access the init parameter and its value. The code initializes the FilterConfig object in its init method, which is called once when the web container creates an instance of the filter. The code then gets the value of the filter's init parameter by calling:

String id = config.getInitParameter("log-id");

Make sure that the code checks whether the return value from getInitParameter is null before the code does something with that object.

Example 19-7. Accessing an init param value in a filter

package com.jspservletcookbook; import javax.servlet.*; import javax.servlet.http.*; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; ...

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