Writing Servlet Filters

A filter is an object that can transform the header and content (or both) of a request or response

The main tasks that a filter can perform are as follows:

  • Query the request and act accordingly.

  • Block the request-and-response pair from passing any further.

  • Modify the request headers and data. You do this by providing a customized version of the request.

  • Modify the response headers and data. You do this by providing a customized version of the response.

  • Interact with external resources.

import java.io.*;
import java.util.*;
 
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;
import javax.servlet.http.HttpServletResponse;


public class SecurityFilter implements Filter {
     
    public void destroy() {
    }
 
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
 
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String url = request.getServletPath();
        boolean hasParameter = false;
		
		// The following generates a page showing all the request parameters
		PrintWriter out = resp.getWriter();
		resp.setContentType("text/plain");		
         
		out.println(url);
		 
		// Get the values of all request parameters
		Enumeration enum = req.getParameterNames();
		for (; enum.hasMoreElements(); ) {
			// Get the name of the request parameter
			name = (String)enum.nextElement();
			out.println(name);

			// Get the value of the request parameter
			value = req.getParameter(name);

			// If the request parameter can appear more than once in the query string, get all values
			String[] values = req.getParameterValues(name);

			for (int i=0; i < values.length; i++) {
				out.println("    "+values[i]);
			}
		}
         
        chain.doFilter(req, res);
    }
 
    public void init(FilterConfig config) throws ServletException {
	
    }
}



Oracle: Filtering Requests and Responses