Recipe 19.1 Mapping a Filter to a Servlet


You want to map or apply a filter to an individual servlet.


Use the filter and filter-mapping elements in web.xml to associate the filter with the servlet.


The web container finds out about the filters that you want to apply to a servlet by using information in the deployment descriptor. The filter element associates a filter name with a Java class that implements the javax.servlet.Filter interface. The filter-mapping element then associates individual filters with URL mappings or paths, similar to the servlet-mapping element that you have probably used before in web.xml . Example 19-1 shows a deployment descriptor from the servlet API v2.3 that includes the mapping of a filter named LogFilter to the servlet path /requestheaders .

Example 19-1. Mapping a filter to a servlet
 <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app     PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"            "" > <web-app>  <!-- register the filter --> <filter>     <filter-name>LogFilter</filter-name>     <filter-class>com.jspservletcookbook.LogFilter</filter-class> </filter> <filter-mapping>     <filter-name>LogFilter</filter-name>     <url-pattern>/requestheaders</url-pattern> </filter-mapping> <!-- register the servlet to which the filter is mapped --> <servlet>     <servlet-name>requestheaders</servlet-name>     <servlet-class>com.jspservletcookbook.RequestHeaderView</servlet-class> </servlet> <!-- Here is the URL mapping for the requestheaders servlet --> <servlet-mapping>     <servlet-name>requestheaders</servlet-name>     <url-pattern>/requestheaders</url-pattern> </servlet-mapping>  </web-app> 

When a client sends a request to the servlet path /requestheaders , the web container applies the LogFilter filter to the request. This servlet path, as in:


is the only servlet path to which this filter is applied. As you might have guessed, the LogFilter logs some information about the request before the request continues along to its servlet destination. Example 19-2 shows the filter class for the LogFilter in Example 19-1.

This filter class provides the additional benefit of showing you how to log a message inside of a filter!

Make sure to:

  • Create the filter with a constructor that does not take any parameters

  • Give the filter class a package name

  • Store the filter in the WEB-INF/classes directory of the web application, including its package- related directories

  • Map the filter to the servlet in web.xml , as in Example 19-1

Example 19-2. A filter that logs some information
 package com.jspservletcookbook; import javax.servlet.*; import javax.servlet.http.*; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class LogFilter implements Filter {          private FilterConfig config;     private Logger log;          // Creates new LogFilter     public LogFilter( ) {}        public void  init(FilterConfig filterConfig) throws ServletException{            this.config = filterConfig;       //load the configuration for this application's loggers using the       // file       PropertyConfigurator.configure(config.getServletContext( ).         getRealPath("/") +             "WEB-INF/classes/");       log = Logger.getLogger(LogFilter.class);"Logger instantiated in "+ getClass( ).getName( ));   }//init        public void  doFilter(ServletRequest request, ServletResponse response,         FilterChain chain) throws, ServletException {         HttpServletRequest req = null;             if (log != null && (request instanceof HttpServletRequest)){                    req = (HttpServletRequest) request;              "Request received from: " + req.getRemoteHost( ) + " for: " +                 req.getRequestURL( )); }              //pass request back down the filter chain        chain.doFilter(request,response);   }// doFilter        public void destroy( ){       /*called before the Filter instance is removed          from service by the web container*/       log = null;    } } 

This filter logs the remote host of the client request and the URL that the client requested . Here is an example of the logged information:

 INFO - Request received from: localhost for: http://localhost:8080/home/requestheaders 

The filter uses the log4j library (see Chapter 14) from the Apache Software Foundation.

Since the first parameter to the filter's dofilter( ) method is a javax.servlet.ServletRequest type, this parameter must be cast to an HttpServletRequest to call methods such as HttpServletRequest.getRemoteHost( ) .

See Also

Recipe 7.9 on using a filter to read request parameter values; Recipe 11.11 on using a filter to monitor session attributes; Recipe 18.3 on using a filter to alter the request; Recipe 19.2-Recipe 19.4 on mapping filters to web components ; Recipe 19.5 on configuring filter initialization parameters; Recipe 19.6 on blocking requests ; Recipe 19.7 on filtering the HttpServletResponse ; Recipe 19.8 on using filters with RequestDispatchers ; Recipe 19.9 on using filters to check request parameters; Recipe 19.10 on using filters to disallow requests from certain IP addresses.

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326 © 2008-2017.
If you may any questions please contact us: