2 Minutes To Code (β Version)

Java Servlets - 2 minute tutorial

It's time to write your first filter

Let's write our first servlet filter.

A filter needs to implement javax.servlet.Filter interface and implement the the methods init(..), doFilter(..), destroy(..). Of these, you can use the init(..) and destroy(..) methods given below verbatim, unless you have some other special requirement.

The main logic of the filter is put in the doFilter(..) method in line no. 24. Notice the call to FilterChain.doFilter(..) method in line no. 32. Now this is the complete flow :
  1. First web server receives the http request.

  2. All applicable filters are found. Then the doFilter(..) method of first filter is called.

  3. In this doFilter(..) method, the filter does its processing, and then calls the FilterChain.doFilter(..) method

  4. In the FilterChain.doFilter(..) method, other filters are found, and same process is repeated.

  5. When the last filter calls FilterChain.doFilter(..), the servlet's doGet(..), foPost(..) or other http method specific api is called.

  6. When the servlet's method returns, then the control returns to the last filter to teh line of code after FilterChain.doFilter(..) method ie. line number 33 in the code below.

  7. And then, all filters are called in the reverse order.

package com.techfundaes.servletsBag;

import java.io.IOException;
import java.rmi.ServerException;

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.HttpServletRequest;

public class MyFilter implements Filter 
{
	private FilterConfig filterConfig;
	

	public void init(FilterConfig arg0) throws ServletException
	{
		this.filterConfig = filterConfig;
	}
	
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException
	{
		HttpServletRequest request = (HttpServletRequest) req;
		
		String timeUnits = filterConfig.getInitParameter("timeUnits");
		if( request.getParameter("superUser") != null )
			request.setAttribute("adminPrivileges", "true");
	
		filterChain.doFilter(req, res);
		
		System.out.println("Done !");
	}
	
	public void destroy()
	{
		
	}
}