Implementing Filters in a JSP application

JSP Filter

JSP Filters – How to implement it?


JSP has a special feature which introduces the concept of filters. The work of these filters is to intercept any request en route to the JSP or the Java servlet. It can also modify to update the response of the server before it reaching the client. Thus, a filter is an extremely important part of a web application as it does a certain function before and after a request. There can be many uses for a filter, like for securing the server and the information, for implementing a logging logic or for compressing the data being sent to the user. These filters have different functions, like encryption, auditing, logging and authentication of the client and the data.

In this article, we will know more about these filters. We will also implement a sample filter using JSP pages.

What is the life cycle of a JSP filter?

For understanding how a JSP filter works, you’ll need to know about its life cycle first. It is quite simple. Actually, a life cycle of a JSP filter means the complete process, starting from its creation and ending with its destruction. This life cycle is very similar to a life cycle of a servlet. There are four major stages in the JSP’s life cycle, which are the compilation, initialization, execution and the clean-up. Each part is described below.

Compilation stage

When a request is first made by a browser, the engine checks if it needs to compile any Java server pages or not. If the requested pages haven’t been compiled earlier or have been modified, then that engine compiles the page. It has three main processes, i.e. parsing the page, turning it into a servlet and then compiling it.

Initialisation stage

When the container loads the compiled JSPs, it issues a method known as jspInit () before processing the request. The initialisation process is done once with this method. This is used for initializing resources like tables, database connections and files etc.

Execution stage

This stage includes every kind of interactions with the JSP until its termination. When the JSP has been loaded in the browser and initialised too, the engine issues a _jspService () method. This method is issued one time per user and helps in the generation of server responses.

Clean-up stage

The last stage of the JSP’s life is the destruction phrase or the clean-up stage. This is the stage when the JSP is destroyed after its use. For this, the method jspDestroy () is used. This method can be used for cleaning up before destroying the page.

What are the different filters?

There are different usages of filters in JSP, two main usages being the interception of requests from the client and modification of the responses from the server. Thus, there are many different types of filters.

Some of the different types of filters include data compression filters, access triggering filters, encryption filters, image converting filters, authentication filters, MIME-TYPE filters, logging filters and token filters.

What are the interfaces/methods?

Methods are a very important part of filters in JSP. The filters are classes in Java which uses the interface javax.servlet.Filter. These interfaces have three main methods. These three methods are described in detail in this section.

  • public void doFilter (ServletResponse, ServletRequest and FilterChain)

The public void doFilter method is used by the container of the JSP whenever a request or a response is made, i.e. this method is issued whenever a pair of request and response is passed through the filter chain. This pair is generated by a client’s request which arrives from the client end of the chain.

  • public void init (FilterConfig filterConfig)

The public void init method is used by the JSP’s web container when it wants to signify that the JSP has been successfully initiated and is ready for use.

  • public void destroy()

The public void destroy method is used by the web container to signify that the filter is no longer required and is taken out of service. This means that all the database connections are deleted and the filter is ready to be destroyed.

Environment setup

For the environment setup you need to follow the following steps

1) Download and install JDK. Set the PATH and JAVA_HOME as shown below.

set PATH=C:\ jdk1.6.0_45\bin;%PATH%

set JAVA_HOME=C:\ jdk1.6.0_45

2) Download and install tomcat web server. Here you can download the service installer file for easy installation.

3) Set up class path for servlet class. This is only for J2SE version.

set CATALINA=C:\apache-tomcat-7.0.70

set CLASSPATH=%CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%

Now the setup is complete. Lets check one example in the next section.

Sample application – JSP filter

In this section we will write a filter by using JSP pages and filter class. Before going into the coding we need to keep the following points in mind.

  • JSP filter is a simple Java class which implements javax.servlet.Filter interface.
  • Filters are defined in the web.xml file in a particular order. And these filters are called according to this order. Each filter is mapped with an URL pattern or JSP files.
  • When the web container starts-up, an instance of each filter is created for execution.

Let us check components one by one.

This is the filter implementation Java class which is called for any client request. It takes the initialization parameter values from the web.xml file and prints the client URI and time stamp.

Listing 1: This is the filter class (

Package com.techalpine.filter


import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class DemoJspFilter implements Filter  {

   // This is the initialization method

   public void  init(FilterConfig confg)

                         throws ServletException{

      //Get initialization parameters

      String initParam = confg.getInitParameter(“init-param”); 

      //Check initialization parameter values

      System.out.println(“Initialization Parameters: ” + initParam);


   //This is the execution method

   public void  doFilter(ServletRequest req,

                 ServletResponse res,

                 FilterChain fltrchain)

                 throws, ServletException {

      // Get client URI.  

      String clientURI = req.getRequestURI();

      // Print client URI and time stamp

      System.out.println(“Client URI: “+ clientURI + “, Time Stamp: “

                                       + new Date().toString());

      // Pass data to the filter chain



   // This is the last life cycle method

   public void destroy( ){

    // This is the clean-up life cycle method



This is the configuration file where all the filters are defined in a particular order and then URL mapping is added. Here we have configured one filter and its corresponding URL mapping. Multiple filters can be added and placed in a proper sequence.

Listing 2: This is the configuration file (web.xml)






                  <param-value>Demo init filter parameters</param-value>







Now all the components are ready for testing. Compile the Java class and place it in the webapps/ROOT/WEB-INF/classes folder (Tomcat). The mapping is defined as (/*), so any calls to JSP pages will execute the filter class and log the output in web server log. The log will contain client URI and time stamp values.


Filters are a very important part of JSP and servlets because they regulate the flow of data from the client to the servlet and vice versa. They can update the server’s response and modify the client’s request. Thus, they are useful for security and administrative reasons too. Also, filters are extremely crucial for the proper working of web apps. A filter can be written quite easily in a URL pattern. While filter-like logics can also be implemented in JSPs directly, this process can prove to be very tiring and require to be very precisely coded. There are many different types of filters for different uses. Also, there are different methods for the JSP’s proper interaction with the filters. When programming, filters can seem daunting at first but is really very easy to implement.


Tagged on: , , ,
============================================= ============================================== Buy TechAlpine Books on Amazon
============================================== ----------------------------------------------------------------

Enjoy this blog? Please spread the word :)

Follow by Email