This section contains the introduction to Servlet filters
Introduction to Servlet filters
A filter is an object that can transform a request or alter a response. Filters not create a response like servlet. It process request before it reaches to a servlet and can process response before it leaves to a servlet.
For implementing servlet we need to import javax.servlet.Filter . This class defines three methods :
- void init(FilterConfig config) throws ServletException :
Sets the filter's configuration object.
- void destroy() :
For destroying the filter's configuration instance.
- void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException:
Perform the actual filter work.
Example :
This filter records the duration of all request.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class TimerFilter implements Filter { private FilterConfig config = null; public void init(FilterConfig config) throws ServletException { this.config = config; } public void destroy() { config = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long before = System.currentTimeMillis(); chain.doFilter(request, response); long after = System.currentTimeMillis(); String name = ""; if (request instanceof HttpServletRequest) { name = ((HttpServletRequest)request).getRequestURI(); } config.getServletContext().log(name + ": " + (after - before) + "ms"); } }
Output :
Under the "logs" folder of tomcat , if you check the log file, you will find the following log :
Dec 1, 2010 3:27:39 PM org.apache.catalina.core.ApplicationContext log INFO: /ankit/servlet/RewriteServletURL: 0 millisecond
[ 0 ] Comments