Servlet Filter

In this tutorial you will learn about the Filter. A filter is an object that intercepts and alters (if required) the header and content of a request and response from server. Generally it does not create response for themselves. Rather it can be attatched to any kind of web recource.

Servlet Filter

In this tutorial you will learn about the Filter. A filter is an object that intercepts and alters (if required) the header and content of a request and response from server. Generally it does not create response for themselves. Rather it can be attatched to any kind of web recource.

Servlet Filter

Servlet Filter

In this tutorial you will learn about the Filter.

A filter is an object that intercepts and alters (if required) the header and content of a request and response from server. Generally it does not create response for themselves. Rather it can be attatched to any kind of web recource.

Sevral tasks are done by the Filter. Some of the main tasks are as follows :

  • Restrict to pass the request and response any further.
  • Alters (if required) the request & response headers and data.
  • Interact with external resources.
  • Query the request and performs tasks accordingly.

Filter can be used in such areas where it is required to include authentication, logging, image conversion, data compression, encryption, tokenizing streams, XML transformations and so on. There can either zero, one or more filters be configured web resource by filter chaining into a specified order. Filter instance is instantiated when the component are loaded by the web container and the chain which configured web resource by filter chaining is specified at the time of deployment of the component contained by the web application.

Filter Programming

In filter programming following interfaces are required to be implement :

  • Filter
  • FilterChain
  • FilterConfig

javax.servlet package contains these above interfaces.

In the web application if you are interesting in to create an annotated Filter then you are required to use the @WebFilter annotation. This annotation holds metadata of the filter is to be declared. The Filter which is annotated must be defined at least one URL pattern using urlPatterns or the value attribute. When there is only URL pattern attributes on the annotation then use the value attribute or when there are other attributes are also used then use the urlPatterns attribute. It should be noted that when you are using the @WebFilter annotation with your class you must have to implement the javax.servlet.Filter interface. As the doXXXX() method in servlet doFilter() method of Filter interface which is passed request, response, and filter chain objects describes that what a filter will do. Following actions can be done by doFilter() method :

  • Analyse the request header and customize the request and response object if request and response headers and data are like to modifies by the filter..
  • Call the next filter in the chain, calling is made by the doFilter() method by passing ServletRequest and ServletResponse object.
  • Analyse the response header after calling next filter in the chain.
  • If any error is found in processing it throws an exception.

One thing should be noted that when you will use the doFilter method you must have to implement the init() and destroy() method, because for instantiating the filter web container calls the init() method. As the servlet, in filter init() and destroy() methods are also call only once.

example :

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

@WebFilter(urlPatterns={"/*"}, description="Reuest  annotated filter demo")
public class AnnotatedFilterDemo implements Filter
 {
public FilterConfig config = null;

public void init(FilterConfig config) throws ServletException
  { 
this.config = config;
config.getServletContext().log("AnnotatedFilterDemo is initializing");
  }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
 throws IOException, ServletException
  {
long timeBefore = System.currentTimeMillis();
chain.doFilter(request, response);
long timeAfter = System.currentTimeMillis();
String path = ((HttpServletRequest)requset).getRequestURI();
config.getServletContext().log(path + " : "+(timeAfter-timeBefore));
  }
public void destroy()
  {
config.getServletContext().log("AnnotatedFilterDemo has been destroyed");
  }
}

Filter Mappings in web.xml

By the filter mapping web container is to be able to decide that how the filters will be applied to web resources. Mapping of filter in a web.xml  is identified for a web component by name or for web resources by URL pattern and is called the other filters into which order they are mapped in filter mapping list.

web.xml

<filter>
    <filter-name>annotatedFilterDemo</filter-name>
    <filter-class>AnnotatedFilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>annotatedFilterDemo</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Following image describes multiple filter mapping for the servlets :

In this image F1, F2, F3 are filters and S1, S2, S3 are the servlets where F1 is mapped to S1, F2 is mapped to S1, S2, S3 and F3 is mapped to S2, and S3.