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.

package net.viralpatel.sevlet.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;

/**
 * @author BigBird
 * @date 2011-12-6 下午11:07:41
 * @action
 */
public class LogFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		// add code to release any resource
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		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());
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		// Get init parameter
		String testParam = config.getInitParameter("test-param");
		// Print the init parameter
		System.out.println("Test Param:" + testParam);
	}

}

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.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>ServletProject</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<filter>
		<filter-name>LogFilter</filter-name>
		<filter-class>net.viralpatel.sevlet.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>
</web-app>

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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值