Servlet Filter Tutorial

Java Servlet Filter Tutorial explains step by step details of creating a Servlet Filter using Eclipse

Servlet filter filter dynamically manipulate both requests as well as responses and to modify the object contained in the requests or responses

Typically Servlet Filters do not create responses, but they provide universal operations which can be a part of any type of JSP or servlet

Here we are showing an example of hitCounter, so that we can count the exact number of visitors for a site. Here hitcount variable is increased on each request.

You can see the below example, which is demonstrating Servlet Filter Tutorial

Required Libraries

You need to download

  1. Eclipse 3.7
  2. JDK 6
  3. Tomcat 7

Using Servlet 3.0 Annotations

We are not using web.xml, but @WebFilter("/*") annotation

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.annotation.WebFilter;

* Servlet Filter implementation class HitCountServletFilter

public class HitCountServletFilter implements Filter {
private int hitCount;

public void destroy() {

public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain
) throws IOException, ServletException {
// increase counter by one

// Print the counter.
System.out.println("Site visits count :" + hitCount);
("counter", hitCount);
// pass the request along the filter chain
chain.doFilter(request, response);

public void init(FilterConfig fConfig) throws ServletException {
// Reset hit counter.
hitCount = 0;


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hit Count Servlet</title>


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