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

7.9. Using a Filter to Read Parameter Values

Problem

You want to use a filter to intercept form input and read it.

Solution

Use the various getParameter methods of the ServletRequest API to take a look at parameter values in a filter.

Discussion

When you develop a filter for a servlet, your filter class has to implement the javax.servlet.Filter interface. This means that your Filter class has to implement the doFilter(request,response) and destroy( ) methods of that interface. The doFilter method contains the hook to the filtered servlet's parameter values. The doFilter's ServletRequest parameter has the getParameter, getParameterMap, getParameterNames, and getParameterValues methods which allow the filter to peek at a servlet's parameters and values.

First, you have to map the Filter you have designed to the servlet. This chunk of web.xml maps a Filter object to a servlet named Viewer.

<!-- any context-param elements go here -->
<filter>
        <filter-name>ParamSnoop</filter-name>
        <filter-class>com.jspservletcookbook.ParamSnoop</filter-class>
</filter>

<filter-mapping>
        <filter-name>ParamSnoop</filter-name>
        <servlet-name>Viewer</servlet-name>
</filter-mapping>
<!-- web.xml continues  -->

Place the filter class in the WEB-INF/classes directory of your web application, or inside a JAR file that is placed in WEB-INF/lib. The servlet container creates an instance when the container starts up of each filter that is declared in web.xml. The container then executes the filter (calls its doFilter method) ...

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