Servlet - FilterChain

Last Updated : 18 May, 2026

A Servlet Filter Chain is a sequence of filters that are applied to a web resource (Servlet, JSP, or HTML page) before and after the request is processed. It allows multiple filters to work together to handle and modify requests and responses in a structured order.

  • Filters are executed in the order defined in the web.xml file using <filter-mapping>
  • Each filter can process request and response both before and after reaching the target resource
  • Commonly used for authentication, session validation, logging, and request blocking

Working

The below diagram illustrates the working flow of a Servlet Filter Chain, showing how a client request passes through multiple filters before reaching the servlet and how the response returns back through the same chain.

client
FilterChain
  • Client sends a Request: The browser or client initiates the HTTP request to access a web resource.
  • Filter1.java executes: The first filter processes the request (like logging or authentication) and forwards it using chain.doFilter().
  • Filter2.java executes: The second filter further processes the request and again passes control forward using chain.doFilter().
  • MyServlet.java executes: The actual servlet runs and executes the business logic for the request.
  • Response Flow (Reverse Order): The response travels back from servlet → Filter2 → Filter1 → client, allowing filters to process the response as well.

Methods Used in Filter Interface

To create a filter class, we must implement the methods of the javax.servlet.Filter interface. These methods are used to initialize, process requests/responses, and destroy the filter object.

1. init(FilterConfig config)

This method is called by the web container only once when the filter is created. It is used to initialize filter configuration parameters and allocate required resources.

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

2. doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

This method is called whenever a client requests a web resource such as a Servlet or JSP page. It is mainly used for request preprocessing and response postprocessing.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
// request preprocessing

chain.doFilter(request, response);

// response postprocessing
}

3. destroy()

This method is called before removing the filter object from service. It is used to release resources and perform cleanup operations.

public void destroy()
{
// cleanup code
}

Example To Show Step-by-Step Process to Run the FilterChain

This example demonstrates how to create and run a Servlet Filter Chain application using two filters and one servlet.

Step 1: Create Dynamic Web Project

  • Open Eclipse IDE
  • Create a project: ServletFilterchain
  • Select: Dynamic Web Project
  • Click Finish

After completion of above steps the Project created in the Eclipse Working directory and project Directory looks like:

Step 2: Create index.html

This page accepts user input and After clicking submit, the request goes to GfgServlet.

HTML
<html>
<head>
<title> Gfg Filter demo</title>
</head>

<body>
  <b>Enter your name :</b>
  <br/>

  <form action ="GfgServlet">
  Name : <input type = "text"  name = "name" />
  <input type = "submit"  name = "submit" />
  </form>

</body>
</html>

Step 3: Create First Filter Class

This filter executes first in the filter chain and processes the client request before passing it to the next filter.

Java
import java.io.*;
import javax.servlet.*;

public class GfgFilter1 implements Filter {
    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
    // This method is called each time a client requests for
    // a web resource
    // which could be a Servlet or a JSP page i.e.
    // preprocessing request
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println(
            "<b> Filter1 is Filtering the request : </b>");
        out.println("Hello " + request.getParameter("name")
                    + "!");

        out.println("<br/>");
        out.println("<br/>");
        out.println("<br/>");

        // Calling  doFilter() calls the next filter in the
        // chain will execute or if there is no filter then
        // the requested web resource is executed.
        chain.doFilter(request, response);

        out.println("<br/>");
        out.println("<br/>");
        out.println("<br/>");

        // post-processing the request and after the
        // requested web resource is called.
        out.println(
            "<b> Filter2 is Filtering the response : </b>");
        out.println("Bye " + request.getParameter("name")
                    + "!");
    }
}

Step 4: Create Second Filter Class

This filter executes after GfgFilter1 and forwards the processed request to the target servlet.

Java
import java.io.*;
import javax.servlet.*;

public class GfgFilter2 implements Filter {
    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
    // This method is called each time a client requests for
    // a web resource
    // which could be a Servlet or a JSP page i.e.
    // preprocessing request
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println(
            "<b> Filter2 is Filtering the request : </b>");
        out.println("Hello " + request.getParameter("name")
                    + "!");

        out.println("<br/>");
        out.println("<br/>");
        out.println("<br/>");

        // Calling  doFilter() calls the next filter in the
        // chain will execute or if there is no filter then
        // the requested web resource is executed.
        chain.doFilter(request, response);

        out.println("<br/>");
        out.println("<br/>");
        out.println("<br/>");

        // post-processing the request and after the
        // requested web resource is called.
        out.println(
            "<b> Filter1 is Filtering the response : </b>");
        out.println("Bye " + request.getParameter("name")
                    + "!");
    }
}

Step 5: Create Servlet Class

This servlet executes after all filters complete request processing and generates the final response.

Java
import java.io.*;
import javax.servlet.*;
public class GfgServlet extends GenericServlet {
    public void service(ServletRequest request,
                        ServletResponse response)
        throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("GeekssForGeeks servlet is executed.");
    }
}

Step 6: Configure web.xml

Defines filter configuration and execution order and Maps servlet and filters with URL pattern.

XML
<web-app>
  <display-name>GeeksForGeeks FilterChain</display-name>
  
<filter>
     <filter-name>Filter1</filter-name>
    <filter-class>GfgFilter1</filter-class>
</filter>

<filter>
     <filter-name>Filter2</filter-name>
    <filter-class>GfgFilter2</filter-class>
</filter>

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <url-pattern>/GfgServlet</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>Filter2</filter-name>
    <url-pattern>/GfgServlet</url-pattern>
</filter-mapping>

<servlet>
     <servlet-name>Servlet</servlet-name>
    <servlet-class>GfgServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Servlet</servlet-name>
    <url-pattern>/GfgServlet</url-pattern>
</servlet-mapping>

</web-app>

Step 7: Run the Project

  • Right click project -> Run As -> Run on Server
  • Open browser:

http://localhost:8080/ServletFilterchain/index.html

Your Login page will appear on the browser

Output

Click on the submit button and the following screen output will be shown.

Output

Explanation: When the user clicks the submit button, the request first passes through Filter1 and then Filter2 before reaching the servlet. After the servlet executes, the response returns in reverse order through Filter2 and Filter1, and the final output is displayed in the browser.

Comment