How to use filter in JSP

In the previous article, we have seen How form data is processed in JSP using GET and POST. In this article, we will cover How to write Filters in JSP.

In this article, we will cover what is a filter, why we need a filter, its usage, its types, its method, and the Life cycle with a simple example.

What is Filter in JSP?

Filter are classes in JSP and Servlet. Before the client request is processed and after its processing object of Filter is invoked. Filter as the name suggests it is used to filter tasks such as conversion, logging, validation. The Entry of the filter is defined in the web.xml file. If any changes are applied we can change in web.xml file we don’t need to change the entire project.

Why we need a Filter?

In certain conditions when we need to manage sessions in our application and to avoid redundant code in the application. To avoid this, we used Filter in JSP. So, the filter is used in Server Side authentication and logging, etc.

Uses of Filter

  • A filter is used for validation.
  • A filter is used for encryption and decryption.
  • A filter is used for the recording of the incoming requests.
  • A filter class can be used to count the number of visitors to a site.

Types of Filter in JSP

  • Authentication filters
  • Encryption filters
  • Data compression filters
  • MIME chain filters
  • Logging filters
  • Tokenizing filters

JSP Filter Interface

JSP Filter class implement javax.servlet.Filter interface. It provides three methods that mean if a class implements the filter interface has to implement the following method.

  • public void init(FilterConfig): This method indicates that the filter is placed in service.
  • public void doFilter(ServletRequest, ServletResponse, FilterChain): This method is used to perform filtering tasks. It is invoked for every request.
  • public void destroy(): This method is invoked when the filter is destroyed. It is also invoked only once.

JSP Filter Life Cycle

The Life cycle of the JSP filter is controlled by a container and will implement the following method to manage it.

  • init() method is called during the initialization of the filter. We define it on the web.xml file in just like how we do in servlet.
  • doFilter() method called each time after every request. This method performs the actual function of the filter for which it is written.
  • destroy() method is used to perform a cleanup operation.

Let’s see an example of Filter in JSP

In this example, we will understand the Life cycle of the filter by creating two filters and web.xml.

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 * Servlet Filter implementation class FirstFilter
 */
@WebFilter("/FirstFilter")
public class FirstFilter implements Filter {

  /**
   * Default constructor.
   */
  public FirstFilter() {
    // TODO Auto-generated constructor stub
  }

  /**
   * @see Filter#destroy()
   */
  public void destroy() {
    // TODO Auto-generated method stub
    System.out.println("First Filter is destroyed...");
  }

  /**
   * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
   */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    // TODO Auto-generated method stub
    // place your code here
    System.out.println("First Filter is executing...");

    // pass the request along the filter chain
    chain.doFilter(request, response);
  }

  /**
   * @see Filter#init(FilterConfig)
   */
  public void init(FilterConfig fConfig) throws ServletException {
    // TODO Auto-generated method stub
    System.out.println("First Filter is initialiazed...");
  }

}

SecondFilter

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 * Servlet Filter implementation class SecondFilter
 */
@WebFilter("/SecondFilter")
public class SecondFilter implements Filter {

  /**
   * Default constructor.
   */
  public SecondFilter() {
    // TODO Auto-generated constructor stub
  }

  /**
   * @see Filter#destroy()
   */
  public void destroy() {
    // TODO Auto-generated method stub
    System.out.println("Second Filter is destroyed");
  }

  /**
   * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
   */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    // TODO Auto-generated method stub
    // place your code here
    System.out.println("Second Filter is excuting");
    // pass the request along the filter chain
    chain.doFilter(request, response);
  }

  /**
   * @see Filter#init(FilterConfig)
   */
  public void init(FilterConfig fConfig) throws ServletException {
    // TODO Auto-generated method stub
    System.out.println("Second Filter is initialized");
  }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  id="WebApp_ID" version="3.0">
  <display-name>JSPFilter</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>FirstFilter</filter-name>
    <filter-class>FirstFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>FirstFilter</filter-name>
    ,
    <url-pattern>/index.jsp</url-pattern>
  </filter-mapping>

  <filter>
    <filter-name>SecondFilter</filter-name>
    <filter-class>SecondFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>SecondFilter</filter-name>
    ,
    <url-pattern>/index.jsp</url-pattern>
  </filter-mapping>

</web-app>

Just create an index.jsp and run the program on the server and hit the URL and see the output on the console.

INFO: Starting Servlet Engine: Apache Tomcat/7.0.90
First Filter is initialiazed...
Second Filter is initialized
Oct 16, 2020 11:06:26 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8088"]
Oct 16, 2020 11:06:26 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Oct 16, 2020 11:06:26 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 557 ms
First Filter is executing...
Second Filter is excuting
First Filter is executing...
Second Filter is excuting
Oct 16, 2020 11:07:07 AM org.apache.catalina.core.StandardServer await
INFO: A valid shutdown command was received via the shutdown port. Stopping the Server instance.
Oct 16, 2020 11:07:07 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-bio-8088"]
Oct 16, 2020 11:07:07 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-bio-8009"]
Oct 16, 2020 11:07:07 AM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Catalina
First Filter is destroyed...
Second Filter is destroyed

Thus we have seen How to use Filter in JSP pages along with its method.

In the next article of this tutorial, we will discuss How to Handle cookies on the JSP page with a simple example.