Open In App

Java Servlet Filter

Filters are part of Servlet API Since 2.3. Like a Servlet, a filter object is instantiated and managed by the Container and follows a life cycle that is similar to that of a Servlet. A Servlet has 4 stages as depicted below

  1. Instantiate.
  2. Initialize.
  3. Filter.
  4. destroy.



These stages are similar to a servlet’s Instantiate, Initialize, Filter, destroy. The filter is used to pre-process the request and Post-processing the response. A Filter is a java object that performs the Filtering task on either the request to a resource or on the response from a resource or both.

Some of the Applications using Filter

  1. Authentication.
  2. Logging and Auditing Filters
  3. Image Conversion Filters.
  4. Data Compression Filters.
  5. Encryption and Decryption Filters.

Interfaces belong to Filters.

All these interfaces are available in javax.Servlet Package



 Filter

Methods

Method Action performed
init(FilterConfig filterconfig) Called by the web container to indicate to a filter that it is being placed into service
doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) It is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.
destroy() to indicate to a filter that is being out of service. 

Note:

  • Filter information must be provide inside web.xml .
  • Filter is mapped with one or more than one servlet.

File: web.xml




<web-app >
 <servlet>
   <servlet-name>name</servlet-name>
   <servlet-class>Servlet class name</servlet-class>
 </servlet>
 <filter>
<filter-name>name</filter-name>
<filter-class>Filter class name</filter-class>
</filter>
 <filter-mapping>
 <filter-name>name</filter-name>
 <url-pattern>/name</url-pattern>
 </filter-mapping>
<servlet-mapping>
   <servlet-name>name</servlet-name>
   <url-pattern>/url</url-pattern>
 </servlet-mapping>
</web-app>

FilterChain

FilterChain is an interface, which is implemented by a servlet container. Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain to invoke the resource at the end of the chain.

Method: doFilter()

Causes the next Filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.

Return Type: Void

Parameters:  

Syntax:

void doFilter(HttpServletRequest request, HttpServletResponse response)

We can Develop three types of filters as listed below as follows: 

(1) Request Filter: Contain only pre-request Processing logic.

Example: Request count filter, Authentication filter, Authorization filter, Validation filter and etc.

(2) Response Filter: Contain only Post-response generation logic.

Example: Conversion filter, Compression filter and etc.

(3) Request-Response Filter: Contain both pre-request and post-response generation logic.

Example: Performance Test filter.

Implementation: Example of Filter

A. File: index.html




<html>
   <head>
       <title>TODO supply a title</title>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
   </head>
   <body>
     <a href="servlet1">click here</a>  
       <form>    
   <body>
<html>

B. File: MyBlockFilter.java




// Java Program to Illustrate MyBlockFilter
  
// Importing required classes
import java.io.IOException;
import java.io.PrintWriter;
// Importing all servlet classes
import javax.servlet.*;
  
// Class
// Implementing Filter class
public class MyBlockFilter implements Filter {
  
    // Method
    public void init(FilterConfig config)
        throws ServletException
    {
    }
  
    // Method
    public void doFilter(ServletRequest req,
                         ServletResponse resp,
  
                         FilterChain fc)
        throws IOException, ServletException
    {
  
        String ip = req.getRemoteAddr();
  
        PrintWriter out = resp.getWriter();
  
        if (ip.equals("127.0.0.1")) {
            out.print(
                ",<h2>Your ip address is blocked ny this websites</h2>");
        }
  
        else {
            fc.doFilter(req, resp);
        }
    }
  
    // Method
    public void destroy() {}
}

C. File: HelloServlet




import java.io.IOException;
  
import java.io.PrintWriter;
  
import javax.servlet.ServletException;
  
import javax.servlet.http.HttpServlet;
  
import javax.servlet.http.HttpServletRequest;
  
import javax.servlet.http.HttpServletResponse;
  
public class HelloServlet extends HttpServlet {
  
public void doGet(HttpServletRequest request, HttpServletResponse response)
  
  throws ServletException, IOException {
  
 response.setContentType("text/html");
  
 PrintWriter out = response.getWriter();
  
 out.print("<h2>Hello Client welcome to my Website...</h2>");
  
}
  
}

D. File: web.xml




<web-app version="2.5"  
    
 <servlet>
   <servlet-name>HelloServlet</servlet-name>
   <servlet-class>HelloServlet</servlet-class>
 </servlet>
    
 <servlet-mapping>
   <servlet-name>HelloServlet</servlet-name>
   <url-pattern>/servlet1</url-pattern>
 </servlet-mapping>
    
 <filter>
 <filter-name>f1</filter-name>
 <filter-class>MyBlockFilter</filter-class>
 </filter>
    
 <filter-mapping>
 <filter-name>f1</filter-name>
 <url-pattern>/servlet1</url-pattern>
 </filter-mapping>
    
</web-app>

Output:  If our PC IP address is “127.0.0.1″ we cannot  visit the website

                             


Article Tags :