Skip to content
Related Articles

Related Articles

Servlet – FilterChain

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 25 Feb, 2022

A filter is an object that is used throughout the pre-and post-processing stages of a request. Conversion, logging, compression, encryption and decryption, input validation, and other filtering operations are commonly performed using it.

Servlet Filter Chain

We will learn how to correlate a chain of filters with a web resource in this lesson. A Servlet, JSP, or static HTML page might be used as the web resource. We may conduct numerous operations within a web application using the filter function, such as session validation, user authentication and verification, blocking access to a certain online resource, and so on. By implementing the Filter interface, we may build several Filter classes. When a user makes a request to a web resource after associating several Filter classes with it, the associated Filter classes are run before and after the web resource requested by the user is processed, thereby giving a filter to the user request and response. Multiple filters associated with a web resource are performed in the order provided in the deployment descriptor file’s filter-mapping> tag (web.xml).

Methods use for filter chain interface: 

To develop a filter class, we must implement the three javax.servlet.Filter Interface for filtering.

  1. void doInit(FilterConfig config) – The Filter is initialized with this method.
  2. void doFilter(ServletRequest request, ServletResponse, response, FilterChain chain) – When a client requests a web resource, such as a Servlet or a JSP page, the web container calls this function.
  3. void destroy() – The Filter object is destroyed using this procedure. 

Example Project

We’re making a webpage that asks the user to enter his name and then click the submit button, which will call a Servlet. However, before this Servlet is run, two filters connected with it will be run in the sequence provided in the deployment descriptor file’s <filter-mapping> tag (web.xml).

Project Structure:

index.html

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>


Creating Filter:

Following that, we’ll implement the Filter interface and its three methods:

  • init(FilterConfig)
  • doFilter(ServletRequest, ServletResponse, FilterChain )
  • destroy()

We must also invoke the doFilter(ServletRequest, ServletResponse, FilterChain) function of the FilterChain interface from within the doFilter(ServletRequest, ServletResponse, FilterChain) method. Any additional Filter linked to the Servlet is called when the doFilter(request, response) function is called. The requested Servlet is finally executed if there are no more Filters associated with the Servlet. The doFilter(request,response) method returns after the servlet have completed its execution, allowing you to handle Servlet output in the response object.

GfgFilter1.java

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")
                    + "!");
    }
}


GfgFilter2.java

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")
                    + "!");
    }
}


GfgServlet.java is a Servlet class that runs after its accompanying filters have finished running.

GfgServlet.java

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.");
    }
}


web.xml

Every Servlet-based web application must contain a Deployment Descriptor file (an XML file) named web.xml, according to the Java Servlet requirements.

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>


Output:

Run the index.html file on the server and you will get the following output.

Output

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

Output


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!