Open In App

Java Servlet Filter with Example

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A filter is an object that is invoked at the preprocessing and postprocessing of a request on the server, i.e., before and after the execution of a servlet for filtering the request. Filter API (or interface) includes some methods which help us in filtering requests. To understand the concept of Filters, first, you should have an understanding of the concept of Servlets.

Filter 

Why do we use Filters?  

To validate the data coming from the client because through the server the data will be stored in the database. So, only valid data should enter the database. Can we not do this validation (or add filters) on the client-side? We can add filters on the client-side. But if javascript is disabled on the client-side, then the request (or data) will not be checked. Someone might do this intentionally. So, to avoid this, we add Filters on the Server side.

Note: The user-defined servlet filter is pluggable, i.e., its entry is defined in the web.xml file, if we remove the entry of the filter from the web.xml file, it will be removed automatically and we don’t need to change the servlet.  

Advantages of using filter

  • Authentication and authorization of requests for resources. (To check whether the user is valid or not and then forward its request.)
  • Formatting of request body or header before sending it to the servlet. (To format the unformatted data)
  • Compressing the response data sent to the client. (e.g., encrypting)
  • Alter the response by adding some cookies, header information, etc.
  • Input validation. (Most imp)

How to implement a Filter using API Filter? 

  • Remember the following while implementing the Filter API (or interface) –
    • Three methods – init(), doFilter(), destroy (). Have to override these methods. They are the lifecycle methods of a Filter.
    • doFilter will be executed in both preprocessing + postprocessing.
    • doFilter() method takes three arguments – ServletRequest, ServletResponse, FilterChain. With the help of FilterChain, we can forward the request after successful authentication.

Create a user-defined Filter class

Create a class that implements the Filter interface and overrides all its methods, i.e., init(), doFilter(), destroy (). If we don’t override these methods then our class will also become an abstract class. Code written before “chain.doFilter()” will run before the servlet (preprocessing) and code written after “chain.doFilter()” will run after the servlet (post-processing).

Configure the Filter

  • Configure this class (user-defined filter) in the web.xml.
  • Map this class (user-defined filter) in the web.xml to specify when it will be executed.

Example

To run the following programs, I have used Eclipse IDE and Apache Tomcat Server v9.0

1) Create index.html

HTML




<!DOCTYPE html>
<html>
  <head>
      <title>Page Title</title>
  </head>
  <body>
    <h2>Welcome To GFG</h2>
    <form action="GFGServlet">
        <button type="submit">Click here to go to the Servlet</button>
    </form>
  </body>
</html>


2) Create a servlet GFGServlet.java

Java




import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
// Servlet implementation class GFGServlet
@WebServlet("/GFGServlet")
public class GFGServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    // @see HttpServlet#HttpServlet()
    public GFGServlet()
    {
        super();
        // TODO Auto-generated constructor stub
    }
 
    // @see HttpServlet#doGet(HttpServletRequest request,
    // HttpServletResponse response)
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        out.println("<h1>Welcome to the Servlet.");
        // This will print output on console
        System.out.println("GFGServlet is running");
    }
 
    // @see HttpServlet#doPost(HttpServletRequest request,
    // HttpServletResponse response)
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}


3) Create a class GFGFilter.java and implement Filter interface

Java




import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
public class GFGFilter implements Filter {
 
    public void init(FilterConfig filterConfig)
        throws ServletException
    {
    }
 
    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException
    {
 
        PrintWriter out = response.getWriter();
 
        // This will print output on console
        System.out.println(
            "Before filter - Preprocessing before servlet");
 
        // some authentication if required
        chain.doFilter(request, response);
       
        // This will print output on console
        System.out.println(
            "After servlet - Following code will execute after running the servlet - PostProcessing");
    }
 
    public void destroy() {}
}


4) Configuration and mapping of filter in web.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         id="WebApp_ID" version="4.0">
  <display-name>GFGFilter</display-name>
  <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      <welcome-file>default.html</welcome-file>
      <welcome-file>default.htm</welcome-file>
      <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
   
  <filter>
      <filter-name>filter1</filter-name>
      <filter-class>com.app.GFGFilter</filter-class>
  </filter>
   
  <filter-mapping>
      <filter-name>filter1</filter-name>
      <url-pattern>/GFGServlet</url-pattern>
  </filter-mapping>
   
</web-app>




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads