Servlet Filters

A filter is an object that is used to perform filtering tasks such as conversion, log maintain, compression, encryption and decryption, input validation etc. A filter is invoked at the preprocessing and postprocessing of a request. It is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet. So it will be easier to maintain the web application.

A Servlet filter is an object that can intercept HTTP requests targeted at your web application.
A servlet filter can intercept requests both for servlets, JSP's, HTML files or other static content, as illustrated in the diagram below:

Usage of Filter
  • recording all incoming requests
  • logs the IP addresses of the computers from which the requests originate
  • conversion
  • data compression
  • encryption and decryption
  • input validation etc.
Advantage of Filter
  • Filter is pluggable.
  • One filter don't have dependency onto another resource.

Filter API
Like servlet filter have its own API.The javax.servlet package contains the three interfaces of Filter API
  1. Filter
  2. FilterChain
  3. FilterConfig
1) Filter interface
For creating any filter, you must implement the Filter interface.Filter interface provides the life cycle methods for a filter.
  • public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
  • public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain): doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
  • public void destroy():This is invoked only once when filter is taken out of the service.
In order to create a servlet filter you must implement the javax.servlet.Filter interface. Here is an example servlet filter implementation:
import javax.servlet.*;
import java.io.IOException;

/**
*
 */
public class SimpleServletFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain)
    throws IOException, ServletException {

    }

    public void destroy() {
    }
}
When the servlet filter is loaded the first time, its init() method is called, just like with servlets.

When a HTTP request arrives at your web application which the filter intercepts, the filter can inspect the request URI, the request parameters and the request headers, and based on that decide if it wants to block or forward the request to the target servlet, JSP etc.

It is the doFilter() method that does the interception. Here is a sample implementation:
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain filterChain)
throws IOException, ServletException {

    String myParam = request.getParameter("myParam");

    if(!"blockTheRequest".equals(myParam)){
        filterChain.doFilter(request, response);
    }
}

Notice how the doFilter() method checks a request parameter, myParam, to see if it equals the string "blockTheRequest". If not, the request is forwarded to the target of the request, by calling the filterChain.doFilter() method. If this method is not called, the request is not forwarded, but just blocked.

The servlet filter above just ignores the request if the request parameter myParam equals "blockTheRequest". You can also write a different response back to the browser. Just use the ServletResponse object to do so, just like you would inside a servlet.

You may have to cast the ServletResponse to a HttpResponse to obtain a PrintWriter from it. Otherwise you only have the OutputStream available via getOutputStream().

3) FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter method of Filter interface.The FilterChain interface contains only one method:
  • public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the control to the next filter or resource.
Configuring the Servlet Filter in web.xml-
You need to configure the servlet filter in the web.xml file of your web application, before it works. Here is how you do that:
<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>servlets.SimpleServletFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>*.simple</url-pattern>
</filter-mapping>
With this configuration all requests with URL's ending in .simple will be intercepted by the servlet filter. All others will be left untouched.

Servlet Filter Example:
Following is the Servlet Filter Example that would print the clients IP address and current date time. This example would give you basic understanding of Servlet Filter, but you can write more sophisticated filter applications using the same concept:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Implements Filter class
public class LogFilter implements Filter  {
   public void  init(FilterConfig config) 
                         throws ServletException{
      // Get init parameter 
      String testParam = config.getInitParameter("test-param"); 

      //Print the init parameter 
      System.out.println("Test Param: " + testParam); 
   }
   public void  doFilter(ServletRequest request, 
                 ServletResponse response,
                 FilterChain chain) 
                 throws java.io.IOException, ServletException {

      // Get the IP address of client machine.   
      String ipAddress = request.getRemoteAddr();

      // Log the IP address and current timestamp.
      System.out.println("IP "+ ipAddress + ", Time "
                                       + new Date().toString());

      // Pass request back down the filter chain
      chain.doFilter(request,response);
   }
   public void destroy( ){
      /* Called before the Filter instance is removed 
      from service by the web container*/
   }
}
Servlet Filter Mapping in Web.xml:
Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is defined and then mapped to a URL pattern. Create the following entry for filter tag in the deployment descriptor file web.xml
<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
   <param-name>test-param</param-name>
   <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

The above filter would apply to all the servlets because we specified /* in our configuration. You can specicy a particular servlet path if you want to apply filter on few servlets only.

Now try to call any servlet in usual way and you would see generated log in your web server log. You can use Log4J logger to log above log in a separate file.

Using Multiple Filters:
Your web application may define several different filters with a specific purpose. Consider, you define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained above except you need to create a different mapping as mentioned below:
<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
   <param-name>test-param</param-name>
   <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>

<filter>
   <filter-name>AuthenFilter</filter-name>
   <filter-class>AuthenFilter</filter-class>
   <init-param>
   <param-name>test-param</param-name>
   <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>

<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
   <filter-name>AuthenFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>


<<Previous <<   || Index ||   >>Next >>









No comments:

Post a Comment