Open In App

Java Servlet Filter with Example

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

How to implement a Filter using API Filter? 

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

Example

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

1) Create index.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




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




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


Article Tags :