A Brief Introduction to Filter Object in Java

Introduction

This article explains the Filter object of Java servlets. The NetBeans IDE is used for the sample application. This article explains what a filter is and what the filter API is, describes the filter interface, the usage of the filter object, the method of the FilterConfig object, the FilterChain method, etcetera.

What is Filter

A Filter is an optional component of a web application, that provides a mapping between a servlet and a web server and is used to perform common operations such as login, validation providing a single entry point into the application, etcetera.

The following diagram describes the working of a filter.

Fig-1.jpg

1.0: Request is sent to the server

1.1: Filter is invoked

1.2: Preprocessing is completed by the filter and the servlet is invoked.

1.3: The request is processed and control is returned to the filter.

1.4: Post-processing is applied and control is transferred to the server.

1.5: Response is sent to the client.

Filter API

A servlet filter has its own API. The following API exists in the filter interface:

  1. Filter
  2. FilterChain
  3. FilterConfig

The following packages are necessary to use a filter:

  • javax.servlet.Filter
  • javax.servlet.FilterConfig
  • javax.servlet.FilterChain

The Filter interface facilitates development and maintenance of Filters.

The Filter interface provides a life cycle method for filters.

1. init()

This method is invoked only once just after a filter is created. It is used by the server to provide a reference of FilterConfig object to the filter.

Syntax

public void init(FilterConfig config)

2. doFilter()

This method is invoked each time a request is received for the resource to which it is associated.

Syntax

public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException;

3. destroy()

This method is invoked only just before a filter is unloaded.

Syntax

public void destroy();

Usage of filter object

The following is the usage of a filter object:

  • recording all incoming requests
  • data compression
  • input validation
  • logs the IP address of the computer from which the request originates
  • encryption and decryption
  • etcetera

FilterConfig interface

For each interface an object of type config is created by the server. This object is used by the server to provide:

  1. a reference of the servletContext to the filter.
  2. an initialization parameter to the server.

Methods of the FilterConfig interface

The following methods are provided by the FilterConfig interface.

1. getServletContext()

Used to obtain the reference of the ServletContext.

Syntax

public ServletContext getServletContext();

2. getInitParameter()

Used to obtain the value of an initialization paramter.

Syntax

public String getInitParameter(String pname);

3. getInitParameterNames()

Used to obtain the names of all initialization paramters.

Syntax

public Enumeration getInitParameters();

4. getFilterName()

Used to obtain the name of the filter.

Syntax

public String getFilterName();

Implementation of FilterChain is provided by servlet vendors

An object of type FilterChain is created by the server for each request in the processing of which one or more servers participate.

This interface provides the following methods.

1. doFilter()

Used by the server to start the processing of the request and by the filters to continue the processing of the request.

Syntax

public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException;

Understanding the role of FilterChain

One of the repositories of a filter is to invoke the next component after preprocessing. The problem in the fulfillment of this respectively is that a filter doesn't know which component lies in front of it because:

1) A filter may participates in the processing of more then one request

2) In each request there may be a different number of and different types of components; an example will demonstrate the problem.

Scenario: Let's say that there are two filters named F1 & F2 and two servlets named S1 & S2 in an application. Filter F1 is applied on both servlets and filter  F2 is applied only on the S2 servlet, in other words the following will be the flow of processing of the request to the servlets S1 & S2.

Fig-2.jpg

Let's see an example

In this example, we create an application in which we are shown the process flow of a Filter class, or say a filter object. In this app. we create one servlet class "WelcomeServlet" to display and pass the name of user input (provided by the "index.html" file) to Filter class (as "FilterOne" in this example). This name is processed in WelcomeServlet after processing this name is passed to FilterOne that displayed it and displays its own content. Let's start creating this app.

Now we need to perform the following procedure.

Step 1

Open the NetBeans IDE.

Fig-3.jpg

Step 2

Choose "Java Web" -> "Web Application" then click on "Next", as shown below.

Fig-4.jpg

Step 3

Now type your project name and click on "Next".

Fig-5.jpg

Step 4

Choose your server and click on "Finish" as shown below.

Fig-6.jpg

Step 5

Now delete the "index.jsp" file and create a new HTML file with the name "index.html" as shown below.

Fig-7.jpg

Fig-8.jpg

Step 6

Now provide the following code in "index.html".

<!DOCTYPE html>
<html>
    <body>
        <form method="get" action="WelcomeServlet">
            Enter name: <input type="text" name="name"><br>
            <input type="submit" value="submit">
        </form>
    </body>
</html> 

Fig-9.jpg

Step 7

Now create a servlet file as shown below.

Right-click on the project then select "New" -> "Servlet".

Fig-10.jpg

Step 8

Click on "Next" and type your class name as "FilterOne" then click on "Finish" as shown below.

Fig-11.jpg

Step 9

Now provide the following code for it.

FilterOne.java

import java.io.*;

import java.io.PrintWriter;

import javax.servlet.*;

public class FilterOne implements Filter {

    private FilterConfig config;

    @Override

    public void init(FilterConfig config) throws ServletException {

        this.config = config;

        System.out.println("FilterOne is inintialized...");

    }

    @Override

    public void destroy() {

        System.out.println("Filter one is unloaded");

    }

    @Override

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        PrintWriter out = response.getWriter();

        out.println("Filter one is invoked.." + "<br>");

        out.println("<b> This header is generated by Filter " + "One</b><br>");

        out.println("Invoking next Component...." + "<br>");

        chain.doFilter(request, response);

        out.println("Controll is back in Filter One.." + "<br>");

        out.println("<b> This footer is generated by Filter " + "one</b><br>");

        out.println("Post processing completed in Filter One.." + "<br>");

    }

}

Fig-12.jpg

Step 10

Now create another servlet and provide its name as "WelcomeServlet" and provide the following code code for it.

WelcomeServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        PrintWriter out = response.getWriter();

        out.println("Welcome Servelt is invoked.." + "<br>");

        String name = request.getParameter("name");

        HttpSession session = request.getSession();

        session.setAttribute("name", name);

        response.setContentType("text/html");

        out.println("Welcome, " + name + "<br>");

        out.println("Request Processing completed in" + "Servelt One" + "<br>");

    }

}

Fig-13.jpg

Step 11

Now replace the code of the "web.xml" file with following code.

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <filter>

        <filter-name>FilterOne</filter-name>

        <filter-class>FilterOne</filter-class>

    </filter>

    <filter-mapping>

        <filter-name>FilterOne</filter-name>

        <url-pattern>/WelcomeServlet</url-pattern>

    </filter-mapping>

    <servlet>

        <servlet-name>WelcomeServlet</servlet-name>

        <servlet-class>WelcomeServlet</servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>WelcomeServlet</servlet-name>

        <url-pattern>/WelcomeServlet</url-pattern>

    </servlet-mapping>   

</web-app>

Fig-14.jpg

Step 12

Now run your project and see if the output is the same as in the following output:

Fig-15.jpg

Now pass the name "Sandeep".

Fig-16.jpg

Summary: The purpose of designing this article to introduce you to the Filter Object of Java. As you see in the above application the flow of the filter object. Hope you might enjoy it. Thanks for reading.