Filters API In Servlets

Introduction

 
In Servlet applications, a filter can handle security breaches. A filter is a servlet components that provides some useful service to the request and response. The filter lies between the client and the web application. This intercepts the requests to web applications and responses from them. The intercepted requests or responses are manipulated as per the requirements. The request or response manipulation can be checking for the authentication, logging in user information or compressing the data. There can be more than one filter between a client and a web application. This set of filters forms a filter chain. The request and response are processed in each filter of the filter chain sequentially.
 

How Do Filters Work?

 
The filter works as an interface between the client and the web application in the following ways,
 
Intercepts request
 
The request sent to the web application wrapped in the request object is captured by a wrapper object created by the filters. This wrapped request is then manipulated by the filter.
 
Processes the wrapped request
 
The filter then processes the request as per the requirement. The filter contains the method, which actually act over the captured request and modifies the same.
 
Send request to servlet
 
Then the modified request is sent to the appropriate servlet wrapped inside a wrapper object.
 
Processes the wrapped response
 
The request sent from the servlet, which is already wrapped inside a wrapper object is captured by the filter. The filter then processes the request as per the requirement and generates a response. The processing of the response can dynamically change the format of text sent to the client or compress the amount of data sent to the client over the network.
 
Sends response
 
The processed response is then freed by the capture object and captured by the ServletResponse object. Then the response is sent to the client browser.
 

Filter API

 
The filter API brings in all the required interfaces for creating a filter class into the javax.servlet package. It contains three interfaces which create and handle the functionalities of a filter. These are Filter interface.FilterConfig interface and FilterChain interface.
 

Filter Interface

 
The filter interface is mandatory for creating the filter component in the Web container. Create a class that implements this interface so that it can gain access over the methods in the interface.. Some of the methods in the Filter interface are,
 
init()
 
This is called by the servlet container to initialize the filter. It is called once.
 
public void init(FilterConfig filterConfig)throws ServletException
 
doFilter()
 
The doFilter() method of the Filter interface is called by the coordinator each time a request or response is processed.
 
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException , ServletException
 
destroy()
 
This method is called by the servlet container to inform the filter that its service is no longer required.
 
public void destroy()
  1. import java.io.IOException;  
  2. import javax.servlet.Filter;  
  3. import javax.servlet.FilterChain;  
  4. import javax.servlet.FilterConfig;  
  5. import javax.servlet.ServletContext;  
  6. import javax.servlet.ServletException;  
  7. inport javax.servlet.ServletRequest;  
  8. import javax.servlet.ServletResponse;  
  9. public class ProcessTimeFilter implements Filter {  
  10.     private String processingTime = null;  
  11.     private FilterConfig filterConfig = null;  
  12.     public void destroy() //destroy() method is called to release the filter from the operation.    
  13.     {  
  14.         this.processingTime = null;  
  15.         this.filterConfig = null;  
  16.     }  
  17.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
  18.         if (processingTime != null) {  
  19.             request.setAttribute(processingTime, this);  
  20.         }  
  21.         //Assign the current time in millisecond to begin.    
  22.         long begin = System.currentTimrMillis();  
  23.         chain.doFilter(request, response);  
  24.         /* The current time in milli seconds after the control passes from one to the next filter is assigned to the variable end.*/  
  25.         long end = System.currentTimeMillis();  
  26.         //The processing time is calculated and assigned to the FilterConfig object.    
  27.         filterConfig.getServletContext().log(this.toString() + ":" + (end - begin) + "milliseconds");  
  28.     }  
  29.     //The Filter is initialized    
  30.     public void init(FilterConfig filterConfig) throws ServletException {  
  31.         //The filterConfig object is assigned the passed value.    
  32.         this.filterConfig = filterConfig;  
  33.         this.processingTime = filterConfig.getInitParameter("processingTime");  
  34.     }  
  35.     public String toString() {  
  36.         if (filterConfig == nullreturn ("InvokerFilter()");  
  37.         StringBuffer sb = new StringBuffer("InvokeFilter(");  
  38.         sb.append(filterConfig);  
  39.         sb.append(")");  
  40.         return (sb.toString());  
  41.     }  
  42. }  
This code explains a class that extends the Filter interface. This code acts as an interface between a presentation layer application and a servlet. It cannot run without its supporting programs. This calculates the time taken by a servlet to process a request and writes this information to a log file. This uses three methods to carry out the task.
 
The init() method initializes the filter by configuring the filterConfig object. Then the doFilter() method takes the control. It receives the beginning and end time of the processing of servlet request. Then the total processing time is calculated by the doFilter(). After the processes are over , the next filter in the filter chain is invoked by the chain.doFilter() or the servlet is invoked. After the completion of the filter operation, the destroy() method is invoked , which takes the filter out of memory.
 

FilterConfig Interface

 
The FilterConfig interface is vital to initialize the filter. The initialization of filters is done when init() method is called. The init() method retrieves the initial parameters from the FilterConfig object, which is passed to it as argument. It has the following methods.
 
getFilterName()
 
This method returns the name of filter defined in the deployment descriptor file web.xml in web application. Syntax : public String getFilterName().
 
getInitParameter()
 
This method returns the value of the named initialization parameter as a string.. It returns null if the servlet has no attributes.
 
Syntax - public String getInitParameter(String name)
 
getInitParameterNames()
 
This method returns the names of the initialization parameter as an enumeration of String objects.
 
Syntax - public Enumeration getInitParameterNames()
 
getServletContext()
 
This method returns the ServletContext object used by the caller too interact with its servlet container and filter.
 
Syntax - public ServletContext getServletContext() 
  1. import javax.servlet.FilterConfig;  
  2. import javax.servlet.ServletContext;  
  3. import java.util.Enumeration;  
  4. import java.util.Hashtable;  
  5. public class MyFilter implements FilterConfig {  
  6.     private String name;  
  7.     private ServletContext servletContext;  
  8.     private Hashtable initParams;  
  9.     public MyFilter(String name, ServletContext sc, Hashtable ip) {  
  10.         name = name;  
  11.         servletContext = sc;  
  12.         initParams = ip;  
  13.     }  
  14.     public String getFilterName() {  
  15.         return name;  
  16.     }  
  17.     public ServletContext getServletContext() {  
  18.         return servletContext;  
  19.     }  
  20.     public String getInitParameter(String s) {  
  21.         return (String) initParams.get(s);  
  22.     }  
  23.     public Enumeration getInitParameterNames() {  
  24.         return initParams.keys();  
  25.     }  
  26. }  
This source code illustrates the use of the methods in the FilterConfig interface. This program retrieves the initialization parameters using the getInitParameter() method. You can store the parameter names in enumerated variables using the getInitParameterNames() method. The getFilterName() method gets the name of the filter and the getServletContext() method retrieves the ServletContext object.
 

FilterChain Interface

 
This interface supports the concepts of filter chain in an application. An object of FilterChain has all the information about the sequence of control flow among a set of filters in a filter chain from the web.xml file. It contains the doFilter (request, response) method, which invokes the next filter in the line of action in a Web application. The below code shows the doFilter(request, response) method is invoked by an object of the FilterChain interface. This is not a standalone program. It needs servlet to run.
  1. public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOEXception, ServletException {  
  2.     try {  
  3.         //This method invokes the next method in the filter chain.     
  4.         filterChain.doFilter(request, response);  
  5.     } catch () {  
  6.         //catch statement    
  7.     }  
  8. }  
  9. public void destroy() {  
  10.         public void init(FilterConfig filterConfig) {}  
This source code illustrate that the filterChain object of FilterChain interface is invoking the doFilter(request, response) method.
 

Conclusion

 
A filter is a servlet component that provides some useful service to the request and response. A filter works as an interface between the client and the web application and performs intercept requests, processes the wrapped request, sends requests to servlet, and sends responses. The filter API brings in all the required interfaces for creating a filter class into the javax.servlet package. The filter interface is mandatory for creating the filter component in the Web container. The FilterConfig interface is vital to initialize the filter.