Wednesday, October 23, 2013

What is a filter and how do I use it?
Author: Deron Eriksson
Description: This tutorial describes filters and how to use them.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20


Page:    1 2 >

A filter offers a useful way of performing filtered functionality in a JavaSW web application. Typically, filters do not generate content themselves, although in this example, the filter will generate some minimal content to show how it is called. A filter implements the javax.servlet.Filter interface. The primary filter functionality is implemented by the doFilter() method of the filter.
A filter is typically used to perform a particular piece of functionality either before or after the primary functionality of a web application is performed. As an example, if a request is made for a particular resource such as a servletW and a filter is used, the filter code may execute and then pass the user on to the servlet. As a further example, the filter might determine that the user does not have permissions to access a particular servlet, and it might send the user to an error page rather than to the requested resource.
Here we can see an example of a filter declared in web.xmlW. Notice that init parameters can be passed to a filter, just like they can be passed to a servlet. Notice that the filter-mapping has the url-pattern of /*. This routes all requests to the web application through the MyFilter filter.

web.xml

 version="1.0" encoding="ISO-8859-1"?>
 version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	
		MyFilter
com.cakes.MyFilter my-param my-param-value MyFilter /* TestServlet com.cakes.TestServlet TestServlet /test index.jsp
Here is code for a very basic servlet that will will access, the TestServlet class.

TestServlet.java

package com.cakes;

import java.io.IOException;
import java.io.PrintWriter;

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

public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		performTask(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		performTask(request, response);
	}

	private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("TestServlet says hi");
	}

}
Here is a filter, the MyFilter class. This filter will write content to the response, although this is not typical for a filter, since usually they pass content generation off to a servlet or a JSPW. This filter will display the value of the my-param init parameter, and it will also display the values of any request parameters.

MyFilter.java

package com.cakes;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFilter implements Filter {

	FilterConfig filterConfig = null;

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

	public void destroy() {
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		servletResponse.setContentType("text/html");
		
		PrintWriter out = servletResponse.getWriter();
		out.println("my-param (InitParameter): " + filterConfig.getInitParameter("my-param"));
		out.println("

Parameters:
");
		Enumeration parameterNames = servletRequest.getParameterNames();
		if (parameterNames.hasMoreElements()) {
			while (parameterNames.hasMoreElements()) {
				String name = parameterNames.nextElement();
				String value = servletRequest.getParameter(name);
				out.println("name:" + name + ", value: " + value + "
");
			}
		} else {
			out.println("---None---
");
		}
		out.println("
Start Regular Content:

"
); filterChain.doFilter(servletRequest, servletResponse); out.println("
End Regular Content: "
); } }
I also created a very basic JSP, the index.jsp:

index.jsp

index.jsp says hi
I created a filter-test project will the following structure:
'filter-test' project
I fired up the application in TomcatSW and made a request for the TestServlet via the /test mapping in web.xmlW. As you can see, the MyFilter class is executed, and in the 'Regular Content' section we can see the regular content served up by the servletW.
http://localhost:8080/filter-test/test
I added a couple parameter name/value pairs to the URL, and you can see that the filter displays the request parameters and their values.
http://localhost:8080/filter-test/test?a=b&c=d
As an additional test, I hit the index.jsp page and passed in a couple parameter name/value pairs on the URL, and you can once again see that the filter doFilter() method gets executed when index.jsp is requested by the browser.
http://localhost:8080/filter-test/index.jsp?e=f&g=h
As you can see, filters are a great of performing a set of functionality when a particular resource or set of resources is requested.

No comments: