Open In App

Java Servlet Filter

Last Updated : 05 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A Servlet Filter is an object that performs filtering tasks on either the request to a resource, the response from a resource or both. Filters are part of the servlet specification and are used to intercept client requests, modifying or examining the request or response.

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 and Destroy methods. The filter is used to pre-process the request and post-process 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.

The image below shows servlet Filter works in a Java web application by intercepting HTTP requests before they reach resources like JSPs, Servlets or static files

Java Servlet Filter

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

  • Filter.
  • FilterConfig.
  • FilterChain.

All these interfaces are available in javax.Servlet Package let's understand all filter one by one.

 1.Filter

  • Filter is an interface defined in the javax.servlet package.
  • Every custom filter must implement this interface to work with the servlet container.
  • The Filter interface provides three key lifecycle methods first init(), dofilter() and destroy().

Example:

Java
public interface Filter {
    void init(FilterConfig config) throws ServletException;
    void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;
    void destroy();
}

Life cycle method of filter interface:

MethodAction 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.

2. web.xml Configuration

Provides configuration information to a filter.

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>

Explanation:

  • <servlet> defines a servlet with a specific name and class to handle requests.
  • <filter> declares a filter that can intercept requests before they reach the servlet.
  • <filter-mapping> connects the filter to a specific URL pattern, so it knows which requests to act on.
  • <servlet-mapping> links the servlet to a URL pattern, telling the server which servlet should handle which request.
  • The configuration helps control how requests are processed and filtered before reaching the servlet.

3. FilterChain

FilterChain is an interface provided by the servlet container. It is used by filters to pass the request and response to the next filter in the chain or to the target resource (like a servlet or JSP) if it is the last in the chain

Method:

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 Project: Block IP Address:

In this example, we will create a simple web application that uses a Filter to block access based on the client's IP address. If the IP address is "127.0.0.1" (localhost), the user will not be able to access the site.

index.html

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>

Explanation:

  • Defines a basic HTML page structure.
  • Includes page title and meta tags for encoding and responsiveness.
  • Contains a link to trigger a servlet (servlet1).
  • An empty <form> tag is present without inputs or action.
  • Contains HTML errors like duplicate <body> tags and unclosed elements

MyBlockFilter.java

Java
import java.io.IOException;
import java.io.PrintWriter;
// Importing all servlet classes
import javax.servlet.*;

// Implementing Filter class
public class MyBlockFilter implements Filter {

    // Method
    public void init(FilterConfig config)
        throws ServletException
    {
    }

    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() {}
}

Explanation:

  • The class MyBlockFilter implements the Filter interface.
  • The init() method initializes the filter and is executed once during the filter's lifecycle.
  • The doFilter() method checks the IP address of the incoming request.
  • If the IP address is "127.0.0.1", the filter blocks access and displays a message.
  • If the IP is not blocked, the request continues through the filter chain.
  • The destroy() method is called when the filter is taken out of service.

HelloServlet.java

Java
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>");

}

}

Explanation:

  • Class HelloServlet extends HttpServlet, making it a servlet that handles HTTP requests.
  • It overrides the doGet() method to handle GET requests from the client.
  • response.setContentType("text/html") line sets the response type to HTML so the browser can properly render the output.
  • A PrintWriter object is created to send character text to the client.
  • servlet sends a simple HTML message: "Hello Client welcome to my Website." to the client browser.
  • This servlet is typically mapped in the web.xml file or via annotations to respond to a specific URL.

web.xml

XML
<web-app version="2.5"  
xmlns="http://java.sun.com/xml/ns/javaee"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  
 <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  and show below message

Your IP address is blocked by this website

If our PC IP address is not "127.0.0.1" then we can visit the website


Practice Tags :

Similar Reads