How-to: Write a simple servlet filter

What is a filter?
From the JSR 154 specification,

A filter is a reusable piece of code that can transform the content of HTTP requests, responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

How to write a filter?
We can create a filter by writing a new class which implements javax.servlet.Filter. We need to specify the filters in the deployment descriptor so that the container can create a filter chain to process the request/response.

The filters in deployment descriptor:

<web-app>
	<filter>
		<filter-name>MyFilter</filter-name>
		<filter-class>subin.rnd.enterprise.filter.MyFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>MyFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>MyFilter</filter-name>
		<servlet-name>MyServlet</servlet-name>
		<dispatcher>REQUEST</dispatcher>
	</filter-mapping>
</web-app>

We can have a filter (or a chain of filters) processing the request/response. In the above descriptor, we are linking a filter for a URL pattern as well as for a specific servlet. So in the above case, for MyServlet, the filter will get executed twice as we have mapped the filter MyFilter to all URLs and for MyServlet. So the order of execution will be MyFilter.doFilter() > MyFilter.doFilter() > MyServlet.doGet().

MyServlet.java

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet
extends HttpServlet
{
  @Override
  public void doGet(HttpServletRequest request,
    HttpServletResponse response)
  throws ServletException
  {
    System.out.println("doGet()");
    response.setContentType("text/plain");
    ServletUtility.write(response, "Hello world!".getBytes());
  }
}

MyFilter.java

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.http.HttpServletResponse;

public class MyFilter
implements Filter
{
  public void destroy()
  {
  }

  public void doFilter(ServletRequest request, ServletResponse response,
     FilterChain filterChain)
  throws IOException, ServletException
  {
     System.out.println("doFilter()");

     ByteStreamResponseWrapper responseWrapper = null;
     byte[] responseAsBytes = null;
     String processedResponse = null;

     // Creating a response wrapper
     responseWrapper = new ByteStreamResponseWrapper(
        (HttpServletResponse) response);
     filterChain.doFilter(request, responseWrapper);

     // Process the response
     processedResponse = responseWrapper.toString();
     if (null != processedResponse)
     {
       processedResponse = processedResponse.toUpperCase();
       responseAsBytes = processedResponse.getBytes();
     }

     // Writing the response (as bytes) to the servlet output stream
     ServletUtility.write(response, responseAsBytes);
  }

  public void init(FilterConfig filterConfig)
  throws ServletException
  {
    // We can initialize a filter using the init-params here
    // (which we defined in the deployment descriptor - web.xml)
  }
}

Other files
There are two more Java files – ByteStreamResponseWrapper & ServletUtility. ByteStreamResponseWrapper is an extension of javax.servlet.http.HttpServletResponseWrapper with some methods – toString(), getOutputStream() & getWriter() – overriden. ServletUtility is a utility class to write a byte stream to the servlet output stream.

Output
The “Hello world!” from MyServlet is filtered to “HELLO WORLD!”  by MyFilter.

Fig: Output in browser

Output
Fig: Jboss console output

Jboss Console output

Note:
I wanted to put above XML in syntax-highlighted mode; but the WordPress plug-in failed miserably. Tough luck.

Advertisements