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. :)


Facebook  Twitter      Stumbleupon  Delicious
  

24 Comments on “Java Servlet Filter tutorial example using Eclipse & Tomcat”

  • dlogan wrote on 12 March, 2009, 4:43

    Thanks for this guide! It made it VERY easy to get a quick servlet filter up and running to play around!

  • benjamin wrote on 1 April, 2009, 16:48

    Thanks for a simple yet illustratice explaination

  • German wrote on 27 April, 2009, 21:09

    Excelent!!! it’s very usefull.
    thanks…

  • Russell Bateman wrote on 27 April, 2009, 21:28

    Uh, for the neophyte, what if after setting up this project, entering the code, etc. the launch (http://localhost:8080/ServletFilterProject/) produces only a 404? (Eclipse 3.3.2, WST 2.0.2)

  • Viral Patel wrote on 28 April, 2009, 0:18

    Hi Russell,
    I am not sure about the error, but it seems that something is wrong hence your browser is not able to get anything (resource not found!!). Can you try running http://localhost:8080 and check what is coming? Also check if your context root is properly set.

  • Balveer wrote on 23 May, 2009, 17:02

    thank you viral,
    it is ery easy and helpful for me.

  • Viral Patel wrote on 25 May, 2009, 21:24

    @balveer: you welcome. feel free to bookmark this site or registered your email to get articles via email :)

  • Rob wrote on 2 July, 2009, 23:05

    Thanks, this was quite useful. I think I know what problem Russell was encountering:
    The package is set to \"net.viralpatel.servlet.filters\" but in the mapping it\’s trying to find the class \"net.viralpatel.servlet.filter.LogFilter\". If you go into web.xml and add an s to \"filter\" so that it says \"net.viralpatel.filters.LogFilter\" then you should actually get a printout in the console. Otherwise it\’ll throw class not found exception.

  • TechGirl wrote on 15 August, 2009, 1:08

    It’s so nice to find simple blogs that are easy to understand. Nice job, Viral. I will be looking through the remainder of your blogs in hopes to learn more techniques.

  • Viral Patel wrote on 16 August, 2009, 19:26

    @TechGirl, thanks for the comment… feel free to go through articles and also comment or send suggestions if you have any.

  • Namrata wrote on 17 August, 2009, 11:46

    I am unable to find any such option on menu bar.
    i have options file->new->project,package class,interface,enum,annotations,source folder,folder,file,untitled text file,junit test case but there is no option from where i can make jsp/servlet file

  • Viral Patel wrote on 17 August, 2009, 13:10

    Hi Namrata,
    Can you tell me the version of Eclipse you using? Also you must use J2EE perspective while working in this web application.

  • Siddhesh wrote on 16 November, 2009, 10:50

    I did exactly what you said,but i got the following error-
    HTTP Status 404
    description :The requested resource () is not available.

  • Sandeep wrote on 29 November, 2009, 3:06

    Very Useful Example………………………….

  • shyamshara prajapati wrote on 3 December, 2009, 13:36

    Thanks Viral, I know you are a Pro.

  • Viral Patel wrote on 3 December, 2009, 16:07

    @Shyamshara – Thanks for the comment

  • Brian wrote on 19 December, 2009, 10:43

    Remember that a Filter is an interface component, and not a Servlet, so in order for it to render output to the browser, you will want to map it to a Servlet. The reason you will get a requested resource is not available 404, is because there is either no welcome-file-list setup, or you don’t have a servlet mapped to the filter. Viral, this is a great example, but I’m pretty sure you did not post your web.xml in its entirety.

  • George wrote on 22 January, 2010, 15:33

    Hi Viral,
    Similar to what Russell Bateman wrote on 27 April, 2009, 21:28, I get the following along with HTTP Status 404 from Eclipse console:

    Jan 22, 2010 12:27:20 PM org.apache.tomcat.util.digester.Digester endElement
    WARNING: No rules found matching ‘Server/Service/Engine/Host/Content’.
    Jan 22, 2010 12:27:20 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ’source’ to ‘org.eclipse.jst.j2ee.server:ADCDemo’ did not find a matching property.
    Jan 22, 2010 12:27:20 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ’source’ to ‘org.eclipse.jst.jee.server:ServletFilterProject’ did not find a matching property.
    Jan 22, 2010 12:27:20 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;.;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\Apache Software Foundation\Tomcat 6.0;C:\Program Files\Java\jre6;C:\Program Files\Java\jdk1.6.0_16
    Jan 22, 2010 12:27:20 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Jan 22, 2010 12:27:20 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 270 ms
    Jan 22, 2010 12:27:20 PM org.apache.catalina.core.StandardService start
    INFO: Starting service Catalina
    Jan 22, 2010 12:27:20 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.18
    Jan 22, 2010 12:27:21 PM org.apache.catalina.core.StandardContext filterStart
    SEVERE: Exception starting filter LogFilter
    java.lang.ClassNotFoundException: net.viralpatel.servlet.filter.LogFilter
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:249)
    at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:397)
    at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:108)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3709)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4363)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
    Jan 22, 2010 12:27:21 PM org.apache.catalina.core.StandardContext start
    SEVERE: Error filterStart
    Jan 22, 2010 12:27:21 PM org.apache.catalina.core.StandardContext start
    SEVERE: Context [/ServletFilterProject] startup failed due to previous errors
    Jan 22, 2010 12:27:21 PM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    Jan 22, 2010 12:27:21 PM org.apache.jk.common.ChannelSocket init
    INFO: JK: ajp13 listening on /0.0.0.0:8009
    Jan 22, 2010 12:27:21 PM org.apache.jk.server.JkMain start
    INFO: Jk running ID=0 time=0/16 config=null
    Jan 22, 2010 12:27:21 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 213 ms

    Any help?
    Thanks

  • Viral Patel wrote on 22 January, 2010, 16:29

    Hi George, There was a type error in my web.xml. I have updated the code. Here is the change.

    
    	        net.viralpatel.servlet.filters.LogFilter
    
    

    I have changed net.viralpatel.servlet.filter.LogFilter to net.viralpatel.servlet.filters.LogFilter.

  • George wrote on 22 January, 2010, 18:44

    Hi Viral,
    Yes! Silly of me that I was doing Cut n Paste the code. If I was to type I would have noticed the small typo (Missing s in filter(s)).
    Amazing but always true – the devil is in the details…LOL

    Then as Brian wrote on 19 December, 2009, 10:43:
    “Remember that a Filter is an interface component, and not a Servlet, so in order for it to render output to the browser, you will want to map it to a Servlet.” it still has a reason to tgrow a 404.
    But as it prints in the console it’s OK for now.

    I will try writting some code now to build some experience as I am new to Http Sessions and have to learn, so I later come up with more constructive questions..

    Thanks for the quick reply (and the correction to the listing..)
    George

  • Ghada wrote on 7 February, 2010, 14:24

    Nice article.Thanks

  • Hao Nhien wrote on 11 March, 2010, 9:38

    Hi Viral,
    What a good job u’ve done. I have something to ask you. This example is ok when I run the first time, but when I run the second time, I didn’t get the IP as well as the time. I guess the problem because of there’s nothing in destroy method, and we need to put something there to run example again, is that right? (when I close my eclipse and open again and run the example again, then it’s ok). Thank you very much for your article and look forward to hearing from your answer. Thanks a lot

  • Paras Jotangiya wrote on 11 March, 2010, 18:42

    Hi Viral ,
    First of i am thanking you to give nice example. And I want to ask one questions .
    where r u from?? Gujarat??

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.