Intercepting Filter


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


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
Before the servlet description
        <description>This is my cool filter</description>


<!-- also apply to another servlet -->

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

Return to top