Intercepting Filter


Definition

A pluggable component design to intercept incomming requests and outgoing responses, provide common services in a standard manner (independently) without changing core processing code.

Where to use & benefits

Example

To create a basic filter, you need to:

  1. implement Filter interface
  2. implement doFilter method
  3. call doFilter from FilterChain object
  4. register the filter with the appropriate servlets and JSP pages
  5. Mapping the filter to specific pages
  6. disable the invoker servlet

General skeleton program

import javax.servlet.*;
import javax.servlet.http.*;

public class MyFilter implements Filter {
    public void doFilter(ServletRequest request,
			 ServletResponse resonse,
			 FilterChain chain) 
                throws ServletException, IOException {
    

         //work on request and response

        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        //work on config
    }

    public void destroy() {
        //work on clean up
    }
}	

Register and filter mapping

//in web.xml file
<web-app>
...
Before the servlet description
    <filter>
   	<filter-name>MyFilter</filter-name>
        <display-name>MyCoolFilter</display-name>
        <description>This is my cool filter</description>
  	<filter-class>somePackage.MyFilter</filter-class>
        <init-param>
            <param-name>yyy</param-name>
            <param-value>/xxx/zzz</param-value>
        </init-param>
    </filter>

    <filter-mapping>
  	<filter-name>MyFilter</filter-name>
  	<url-pattern>/xxx.jsp</url-pattern>
    </filter-mapping>

<!-- also apply to another servlet -->
    <filter-mapping>
 	<filter-name>MyFilter</filter-name>
  	<servlet-name>xxx</servlet-name>
    </filter-mapping>
...
</web-app>

You may use filter mapping and servlet mapping in web.xml file to disable the invoker servlet to apply the filter.

Return to top