Using Servlet filters in Java web applications

As of the Java Servlet specification version 2.3, a component type, called a filter, can be used in your Java web applications. A filter dynamically intercepts requests and responses and is most often used to transform the information contained in the requests and responses.

One good example of a filter is an XSLT transformation filter. With such a filter, you can serve your content in pure XML format. The filter uses an XSL stylesheet to transform the XML into HTML format. You can also use filters to add more logging to the application, or to add extra security.

The following example demonstrates how you create a filter. In this example we will check the user agent and block all requests coming from Internet Explorer clients.

First, create a file called Compile it and put it somewhere under the shared directory in your Java application server (Tomcat), i.e. …/shared/classes/com/mycompany/trafficfilter/TrafficFilter.class.

Here’s the source:

package com.mycompany.trafficfilter;

import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TrafficFilter implements Filter {

  private FilterConfig filterConfig = null;

  public void doFilter(ServletRequest request,
                       ServletResponse response,
                       FilterChain chain)
  throws IOException, ServletException {
    String browserDet = ((HttpServletRequest) request)
    if (browserDet.indexOf("msie") != -1) {
      PrintWriter out = response.getWriter();
      out.println("<h1>Sorry, page cannot be displayed!</h1>");
    chain.doFilter(request, response);

  public void destroy() {}

  public void init(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;

Next, update your web.xml in the WEB-INF directory of your web application. Add the following and elements:


Restart your application server and browse to your web application, i.e. http://localhost:8080/ or something similar. If you’re using a browser that is not Internet Explorer, you should see your default web page (for instance index.html). If you’re using Internet Explorer, you will see a “Sorry, page cannot be displayed!” message.

Leave a Reply

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