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
Using Servlet 3.0 Annotations
We are not using web.xml, but @WebFilter("/*") annotation
import java.io.IOException;
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
*/
@WebFilter("/*")
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
hitCount++;
// Print the counter.
System.out.println("Site visits count :" + hitCount);
request.setAttribute("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;
}
}
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
*/
@WebFilter("/*")
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
hitCount++;
// Print the counter.
System.out.println("Site visits count :" + hitCount);
request.setAttribute("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;
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Hit Count Servlet</title> </head> <body> <%=request.getAttribute("counter")%> </body> </html>