This section of the tutorial will deal with a part of servlets specification called filters. Filters are used for pre- or post-processing of requests, i.e. for applying common business logic to multiple servlets. This can be logging, security enforcement, transaction management, or any other kind of business logic.
More flexible approach would be to implement this as a filter, which will intercept each request and execute the logging code. This way, we have all logging code in one place. We will provide simple example for this kind of filter.
Imagine, for example, that you need to log time stamp for each request that comes to the server. Naive approach would be to add logging code to every servlet, which is cumbersome, error prone and not very flexible. For example, if you want to change some part of logging code, you would have to do it in every servlet.
Every filter must implement javax.servlet.Filter interface. This interface contains 3 methods which need to be implemented:
- init() - called when filter is being initialized
- destroy() - called to perform clean up when filter is shut down
- doFilter() - perform actual request filtering
The code snippet bellow demonstrates simple filter:
public class SampleFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Filter initialized");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("Request timestamp: " + new Date());
chain.doFilter(request, response);
}
public void destroy() {
System.out.println("Filter destoryed.");
}
}
In inti() and destory() methods, we simply print out filter lifecycle messages. In doFilter() method, we first print request timestamp. The second line will allow request processing to proceed to next filter in chain, or if no other filter exists, to correct request handler defined by a servlet container.
One last thing left is to register the filter in deployment descriptor. We will add the following code snippet to web.xml:
<filter>
<filter-name>sampleFilter</filter-name>
<filter-class>com.beyondrelational.SampleFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sampleFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The tag defines filter's unique name and class. The tag defines URL patter to which filter will apply. In this case, it will apply to all requests.
If you now run the application and access any URL, you should see the following output in Tomcat console:

Find the sample web application here.