Filter in Servlet

As of now, we have discussed Servlet Form data like GET and POST method. In this article we will discuss servlet Filters, what are filters, usage, advantages, etc.

What is Filter in Servlet?

Filter are classes in 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 in servlet. 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 servlet.

Why we need 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 Servlet. 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.

Filter API

The javax.servlet package contains three interfaces of Filter API.

  • Filter
  • FilterChain
  • FilterConfig

Filter Interface

Filter Interface is used to create a filter. It has all the life cycle methods for the filter. The following are the methods in a filter.

  • public void init(): This method is used to initialize the filter. it is invoked only once.
  • public void doFilter(HttpServletRequest request,HttpServletResponse response):This method is used to perform filtering task.It is invoked for every request.
  • public void destroys(): This method is invoked when the filter is destroyed. It is also invoked only once.

FilterChain Interface

The next filter or any resource is invoked by the FilterChain object. It contains only one method.

  • public void doFilter(HttpServletRequest request,HttpServletResponse response):This method passes the control to next filter or any resource such as servlet,etc.

FilterConfig Interface

The web container creates the object of FilterConfig. It is used to get the configuration information from the web.xml file. The following are the methods of FilterConfig Interface.

  • public void init(FilterConfig config): This method is used to initialize the filter. It is invoked only once.
  • public String getInitParameter(String parameterName): This method returns the parameter value for the specified parameter name.
  • public Enumeration getInitParameterNames():This method returns all the parameter names.
  • public ServletContext getServletContext():This method returns the ServletContext object.

Let’s see the Example of Filter in Servlet

In this example, we will see the validation of the login page in the Filter class.

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <form action="MyServlet">
    Username &nbsp;&nbsp;<input type="text" name="uname"><br>
    <br> Password &nbsp;&nbsp;&nbsp;<input type="password"
      name="pass"><br> <input type="submit" value="Login">
  </form>
</body>
</html>

FirstFilter.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
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
  }

  /**
   * @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("in filter");
    // pass the request along the filter chain
    PrintWriter out = response.getWriter();
    String uname = request.getParameter("uname");
    String pass = request.getParameter("pass");
    if (uname.equals("Nicolas") && pass.equals("nic")) {
      chain.doFilter(request, response);
    } else {
      RequestDispatcher rd = request.getRequestDispatcher("index.html");
      rd.forward(request, response);
    }

  }

  public void init(FilterConfig fConfig) throws ServletException {
    // TODO Auto-generated method stub
  }

}

FirstServlet.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 FirstServlet
 */
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public FirstServlet() {
    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
    System.out.println("in servlet");
    PrintWriter out = response.getWriter();
    String uname = request.getParameter("uname");
    out.println("Welcome " + uname);
  }
}

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>FilterDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>abc</servlet-name>
    <servlet-class>FirstServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>abc</servlet-name>
    <url-pattern>/MyServlet</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>FirstFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/MyServlet</url-pattern>
  </filter-mapping>
</web-app>

Output

Let’s see one more example of the filter where we will use FilterConfig Interface

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>FilterCofigExample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>ConfigFilter</filter-name>
    <filter-class>Example</filter-class>
    <init-param>
      <param-name>Name</param-name>
      <param-value>Nicolas</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>ConfigFilter</filter-name>
    <url-pattern>/ConfigFilter</url-pattern>
  </filter-mapping>
</web-app>

Example.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;
import javax.servlet.annotation.WebFilter;

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

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

  /**
   * @see Filter#destroy()
   */
  public void destroy() {
    // TODO Auto-generated method stub
  }

  /**
   * @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

    // 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
    String abc = fConfig.getInitParameter("Name");
    System.out.println("Prameter Value: " + abc);

  }

}

Output

Advantages of Filter in Servlet

  • The filter analyses the user request before the servlet is called.
  • The filer can give an altered response.
  • The filter is pluggable.
  • The filter can help in interacting with external resources.