Servlet Filters

Filters in Servlet with Examples

In this article, I am going to discuss Servlet Filters with Examples. Please read our previous article where we discussed Java Servlet Wrappers. At the end of this article, you will understand the following pointers in detail.

  1. Why Servlet Filters?
  2. What are the Filters?
  3. How to use Filters in Servlet?
  4. Advantages of Filters
  5. Types of Filters in Servlet
  6. Filter Interface
  7. FilterChain Interface
  8. FilterConfig Interface
  9. Servlet Filter Example
  10. Servlet Authentication Filter
  11. Authentication Filter Example
Why Servlet Filters?

Intercepting filter is a special web resource program of a web application that can trap all the requests and responses of other web resource programs. Intercepting filter contains common and global pre-request logic and post response generation logic. In servlet programming, we can use the servlet filter as the “Interceptor” filter of the web application. Without disturbing the existing web resource of a web application if you want to add additional functionality to a web application then use servlet filter support.

In general, in web application development, we will provide the complete application logic in the form of web resources like servlets, JSP, and so on. As part of the web application development, some web resources may require services like Authentication, Authorization, Security, Data compression and decompression, and so on as preprocessing and post-processing. In the above context, to implement all the above preprocessing and post-processing services Servlet API has provided a separate component called Filter.

Why Servlet Filters?

From the above representation when we send a request from the client to the server for a particular web resource then the container will pick up that request, the container will check whether any Filter is associated with the respective web resource, if the container identifies any Filter or Filters then the container will execute that Filters first.

While executing a Filter if the present request is satisfied with all the Filter constraints then only the container will bypass that request to the next Filter or next web resource. If the present request is not satisfied with the Filter constraints then the container will generate the respective response to the client. The filter is a server-side component, it will be executed by the container automatically when it receives the request from the client for a particular web resource.

How to use Filters in Servlet?

If we want to use Filters in our web applications, we have to use the following steps:

Step-1: Prepare Filter class

Step-2: Configure Filter class in web.xml file.

Step-1: Prepare Filter Class

A filter is an object available at server machine, it must implement Filter interface either directly or indirectly.

How to use Filters in Servlet?

While executing a particular Filter in web applications, if we satisfy all the Filter constraints then we need to bypass the request from the present Filter to the next Filter web resource, for this we need to use the following method from FilterChain.

public void dofilter(ServletRequest req, ServletResponse res) throws SE, IOE

While executing a particular web application, when a container identifies a particular Filter to execute, then the container will execute that Filter by following the Filter life cycle.

Filters in Servlet with Examples

In web applications, by default, all the filters are auto-loaded, auto-instantiated, auto-initialized at the time of server startup. So that Filters should not require load-on-startup configuration in web.xml file.

Step-2: Filter class configuration

To configure a filter in the web.xml file we have to use the following XML tags.

<web-app>
 ……..
<filter>
<filter-name>logical_name</filter-name>
<filter-class>Fully qualified name of Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>logical_name</filter-name>
<url-pattern>pattern_name</url-pattern>
  Or
<servlet-name>logical name of servlet</servlet-name>
</filter-mapping>
…………….
</web-app>

If we want to provide a mapping between a Filter and servlet then we have to provide the same URL-pattern for both Filter and servlet or provide the respective servlet logical name along with the <servlet-name> tag in place of <url-pattern> tag under <filter-mapping>.

In web applications, it is possible to use a single Filter for multiple numbers of web resources. To achieve this, we have to use “/*” (directory match) as a URL-pattern to the respective Filter. In web applications, it is possible to provide multiple Filters for a single web resource, in this case, the container will execute all the Filters as per the order in which we provided <filter-mapping> tags in the web.xml file.

Advantages of Filters
  1. It is pluggable
  2. Filter doesn’t have a dependency on another resource.
  3. It has less maintenance.
Types of Filters in Servlet

There are 3 types of filters:

  1. Request Filter: Contains only pre-request processing logic. Example: Req count filter, Authentication filter, Authorization filter, etc.
  2. Response Filter: Contains only post-response generation logic. Example: conversion filter, compression filter, etc.
  3. Request-Response Filter: Contains both pre-request and post request generation logic. Example: performance test filter

Note: Filter program and its target servlet program or JSP program uses the same request, response object. So, the filter program can send data to the servlet program or JSP program by using request attributes.

Filter API

There are three interfaces of Servlet API:

  1. Filter
  2. Filter Chain
  3. Filter Config
Filter Interface

It is an object that performs filtering tasks on either the request to a resource or on the response from a resource or both. It performs filtering in the doFilter method. It is configured in the deployment descriptor of a web application. Each Filter has access to a FilterConfig object by which it can obtain its initialization parameters which is a reference to the ServletContext which it can use.

Methods of Filter
  1. void destroy(): It is called by the web container to indicate to a filter that it is being taken out of service.
  2. void doFilter(ServletRequest request, ServletResponse response. FilterChain chain): It is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.
  3. void init(FilterConfig filterConfig): It is called by the web container to indicate to a filter that it is being placed into service.
FilterChain Interface

It is an object provided by the servlet container to the developer giving a view into the invocation chain of a filtered request for a resource. Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain to invoke the resource at the end of the chain.

Method of FilterChain
  1. void doFilter(ServletRequest request, ServletResponse response): It helps the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.
FilterConfig Interface

It is used by a servlet container to pass information to a filter during initialization.

Methods of FilterConfig
  1. java.lang.String getFilterName(): It returns the filter-name of this filter as defined in the deployment descriptor.
  2. java.lang.String getInitParameter(java.lang.String name): It returns a string containing the value of the named initialization parameter, or null if the parameter does not exist.
  3. java.util.Enumeration getInitParameterNames(): It returns the names of the filter’s initialization parameters as an Enumeration of String objects, or an empty Enumeration if the filter has no initialization parameters.
  4. ServletContext getServletContext(): It returns a reference to the ServletContext in which the caller is executing.
Servlet Filter Example

In this example, we are creating a webpage index.html where you will get a link “click here”. Click on the link which will call a servlet “HelloServlet.java”. But before this Servlet is executed, filter “MyFilter.java” associated with it will be executed which is specified in the deployment descriptor.

index.html
<html>
    <head>
        <title>HttpSession Event Listeners</title>
    </head>
    <body>
        <a href="servlet1">click here</a>
    </body>
</html>
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MyFilter implements Filter
{
    FilterConfig config;
    public void init (FilterConfig config) throws ServletException
    {
        this.config = config;
    }

    public void doFilter (ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException
    {
        PrintWriter out = resp.getWriter ();
        String s = config.getInitParameter ("construction");
        if (s.equals ("yes"))
        {
         out.print ("This page is under construction");
        }
        else
        {
         chain.doFilter (req, resp);	// sends request to next resource
        }
    }

    public void destroy ()
    {
    }
}
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
    public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();
        out.print ("<br>welcome to servlet<br>");
    }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/servlet1</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>f1</filter-name>
        <filter-class>MyFilter</filter-class>
        <init-param>
            <param-name>construction</param-name>
            <param-value>no</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>f1</filter-name>
        <url-pattern>/servlet1</url-pattern>
    </filter-mapping>
</web-app>

Output

Servlet Filter Example

Servlet Authentication Filter

It is a special type of security provider that primarily acts as a “helper” to an Authentication provider. It is a provider type that performs pre-and post-processing for authentication functions, including identity assertion. The ServletAuthenticationFilter interface defines the security service provider interface (SSPI) for authentication filters that can be plugged into WebLogic Server. 

Authentication Filter Example

In this example, we are creating a webpage Webpage1.jsp which asks the user to enter his name and password and click the submit button. The given information will be matched against the username and password stored in and initialization parameters of this filter specified in the deployment descriptor file web.xml. We are creating a Filter MyFilter1.java by implementing the Filter interface and by implementing its methods. MyServlet1.java is a servlet class, which is executed after its associated filter is executed.

Webpage1.jsp
<html>
    <head>
        <title>Filters Demo</title>
    </head>
    <body>
        <b> Please enter your details : </b>
        <br />
        <br />
        <br />
        <form action="MyServ">Name : <input type="text" name="username" /> Password :<input type="password" name="password" /> <input type="submit" name="submit" /></form>
    </body>
</html>
MyFilter1.java
import java.io.*;
import javax.servlet.*;
import java.util.*;
public class MyFilter1 implements Filter
{
    FilterConfig config;
    public void init (FilterConfig filterConfig)
    {
        config = filterConfig;
    }

    public void destroy ()
    {
    }

    //This method is called each time a client requests for a web resource i.e. preprocessing request
    public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();

        if (request.getParameter ("username").equals (config.getInitParameter ("username")) && request.getParameter ("password").equals(config. getInitParameter("password")))
        {
         out.println ("Login success!");
         out.println ("<br/>");
         out.println ("<br/>");
         out.println ("<br/>");

            //doFilter() calls the next filter in the chain or the requested web resource(if there is no more filter)
         chain.doFilter (request, response);
        }
        else
        {
         out.println ("Login failed!");
        }

        out.println ("<br/>");
        out.println ("<br/>");
        out.println ("<br/>");

        //post-processing the request and after the requested web resource is called.
        out.println ("<b><i>Message of the day - Never give up!</i></b>");
    }
}
MyServlet1.java
import java.io.*;
import javax.servlet.*;
public class MyServlet1 extends GenericServlet
{
    public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();
        out.println ("You are logged into your account.");
    }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 version="4.0" metadata-complete="true">
    <display-name>Welcome tomcat</display-name>
    <description>
     Welcome tomcat
  </description>
    <filter>
        <filter-name>Filter1</filter-name>
        <filter-class>MyFilter1</filter-class>
        <init-param>
            <param-name>username</param-name>
            <param-value>scott</param-value>
        </init-param>
        <init-param>
            <param-name>password</param-name>
            <param-value>tiger</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Filter1</filter-name>
        <url-pattern>/MyServ</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>MyServlet1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/MyServ</url-pattern>
    </servlet-mapping>
</web-app>
Output

First, execute the Webpage1.jsp page which will ask the user to enter his name and password and click the submit button.

Servlet Authentication Filter

If there is a match of values then the user is presented with the following messages on the window.

Authentication Filter Example

If there is a mismatch of values then the user is presented with the following messages on the window.

Servlet Filters with Examples

In the next article, I am going to discuss CRUD in Servlet. Here, in this article, I try to Servlet Filters with Examples. I hope you enjoy this Servlet Filters with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *