Java Servlet Filter tutorial example using Eclipse & Tomcat

Servlet Filters are the latest components that are added in Servlet 2.3 specifications. These filters are used basically for intercepting and modifying requests and response from server.  Consider a scenario where you want to check session from the every users request and if it is valid then only you want to let the user access the page. You can acheive this by checking sessions on all the servlet pages (or JSP pages) which users queries or you can do this by using Filter.

Let us create a Servlet Filter that just prints the clients ip address and date time. This is just to log users who are accessing the application.

We we use Eclipse for developing our application and Apache Tomcat for deploying and running our application.

Step 1: Create dynamic web project in Eclipse.

Starts eclipse and create a new dynamic web project with name ServletFilterProject. Select Target runtime environment. I have selected Apache Tomcat v6.0, you can select any Tomcat version that you have installed. Click on Finish.

Step 2: Create package & Servlet Filter class.

Create a package for Servlet Filters in your source folder of Project. I have created a package net.viralpatel.servlet.filters. Inside the package, create a Java class file called LogFilter.java.

Step 3: Writting Servlet Filter class code.

Modify the LogFilter class and add following code into it.

package net.viralpatel.servlet.filters;

import java.io.IOException;
import java.util.Date;

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.http.HttpServletRequest;

public class LogFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		
		//Get the IP address of client machine.
		String ipAddress = request.getRemoteAddr();
		
		//Log the IP address and current timestamp.
		System.out.println("IP "+ipAddress + ", Time " 
							+ new Date().toString());
		
		chain.doFilter(req, res);
	}
	public void init(FilterConfig config) throws ServletException {
		
		//Get init parameter
		String testParam = config.getInitParameter("test-param");
		
		//Print the init parameter
		System.out.println("Test Param: " + testParam);
	}
	public void destroy() {
		//add code to release any resource
	}
}

In this filter example, we have implemented an interface javax.servlet.Filter and override its methods init, doFilter and destroy.

The init() method is used to initialize any code that is used by Filter. Also note that, init() method will get an object of FilterConfig which contains different Filter level information as well as init parameters which is passed from Web.xml (Deployment descriptor).

The doFilter() method will do the actual logging of information. You can modify this method and add your code which can modify request/session/response, add any attribute in request etc.

The destroy() method is called by the container when it wants to garbage collect the filter. This is usually done when filter is not used for long time and server wants to allocate memory for other applications.

Step 4: Create Servlet Filter Mapping in Web.xml

Open web.xml file from WEB-INF directory of your Project and add following entry for filter tag.

<filter>
	<filter-name>LogFilter</filter-name>
	<filter-class>
		net.viralpatel.servlet.filters.LogFilter
	</filter-class>
	<init-param>
		<param-name>test-param</param-name>
		<param-value>This parameter is for testing.</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>LogFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

In this entry, we have added LogFilter class in Web xml and mapped it with URL /*. Hence any request from client will generated a call to this filter. Also we have passed a parameter test-param. This is just to show how to pass and retrieve a parameter in servlet filter.

Step 5: Execute the web application

We are done with the coding part of Servlet Filter example. Now execute the project by Run -> Run As -> Run on server (shortcut Alt+Shift+X, R).
Check the console you will see the output that we print using System.out.

Change the code in the way you want your filter to work.

Let me know your comments and suggestions. :)



77 Comments

  • parteek 26 December, 2012, 19:53

    thanku so much

  • Anji 11 February, 2013, 18:52

    Hi ,

    Please help me to solve the below problem ,

    SessionValidator
    com.tecnotree.filters.SessionValidator

    SessionValidator
    /ProjectMng/*

    SessionValidator Filter is not calling

    if i changed the /* then Filter is getting called
    Please let me konw why the filter is not calling for the /ProjectMng/*

  • vaibhav 22 March, 2013, 16:39

    Thanks a lot. I am a big fan of your’s

  • Vicky Thakor 13 May, 2013, 18:48

    I want to handle cache for my static domain. It only delivers *.js,*.css and images. I want to set expiry header for that. (i.e ; static.domain.com) i can set expiry header for (www.domain.com) . My application is in java and running on tomcat 7. do you have any idea about that?

  • vara prasad 28 May, 2013, 20:19

    Nice

  • karmveer 29 June, 2013, 16:38

    can i apply a single filter on a group of jsp using single mapping in web.xml .

  • nginx tomcat guy 15 July, 2013, 18:56

    Thanks for the filter example. Simple but good starting point

  • Lokesh 9 August, 2013, 12:54

    Please explain what is the use of FilterChain and what chain.doFilter will do.

  • Priyank 30 September, 2013, 19:30

    Thank you. This worked :)

  • Abhishek 11 November, 2013, 13:02

    Hi Viral,
    Its Great…but got
    output like this..

    IP Adress=127.0.0.1
    IP 127.0.0.1, Time Mon Nov 11 12:57:07 IST 2013
    Test Param: This parameter for testing

    But Shows loop back address(i.e.127.0.0.1) instead of my PC’s IP address,
    plz provide solution.
    Thanks & Regards..

    • fgdf 20 November, 2013, 11:20

      java.net.InetAddress.getLocalHost().getHostAddress();

  • abcd 30 November, 2013, 11:48

    hi,
    I have one question, is it possible to implement all the client side validations we do with javascript in filters ? Because at times, we do face issues with the javascript.

  • vanitha 2 December, 2013, 14:30

    i am not able to get it fully but okay!

  • Bharat Desai 11 December, 2013, 14:53

    thank you for giving me solution. this is very helpfull to me . and i accept that i learn so much things from this site.

  • Kieu Tien Cuong 20 December, 2013, 6:29

    Thank you. Very clear tutorial. It help me saving a lot of time.

  • Asmita 28 December, 2013, 12:23

    please provide an appropriate example for netbeans ide also

  • Lakshmikanth 25 April, 2014, 16:08

    thanks!!. That was pretty much clear and gave me a break through in understanding ServletFilters

  • borat 26 May, 2014, 1:05

    Your code gives me a 404 error. I posted it at stackoverflow. Please help.
    https://stackoverflow.com/questions/23859208/simple-servlet-filter-is-not-working-error-404

  • harinath 12 June, 2014, 7:29

    Hi ,
    i’m new to spring. i have to servlet filter in spring mvc. frame work. if you any sample source code , Please post here

  • gs 12 June, 2014, 13:38

    I am creating a project where I have a login screen, which is used for user to login into the
    Application.after login if iam trying to open the same page in next tab it has to show the already login page to that what code has to write

    • Justin 14 June, 2014, 13:43

      Try with java script.

  • gs 12 June, 2014, 17:03

    can u give any suggetions for the above requirement

  • mahesh 22 June, 2014, 12:26

    thank you

  • Seetesh 24 July, 2014, 9:47

    Can we add more than 1 filter to a servlet or a jsp page

  • abd Erahim 7 August, 2014, 13:38

    a good tutorial,
    Viral Patel, if you don’t mind, this is a code snippet that illustrate a real world example of servlet filters, http://fivesnippets.blogspot.com/2014/08/servlet-filter-for-ddos-spam-etc.html

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *