2013-07-23

What is a filter?

A filter is an object that can transform a request or modify a response. Filters are not servlets; they don’t actually create a response. They are preprocessors of the request before it reaches a servlet/jsp, and/or postprocessors of the response leaving a servlet/jsp page.

Filters are associated with any number of servlets or JSP pages. They examine request coming into servlets or JSP pages then:

– Invoke the resource (i.e., the servlet or JSP page) in the normal manner.

– Invoke the resource with modified request information.

– Invoke the resource but modify the response before sending it to the client.

– Prevent the resource from being invoked and instead redirect to a different resource, return a particular status code, or generate replacement output.

Advantages of Filters

-Filter is pluggable; i.e. we can remove filter definition from web.xml without changing the servlet.

-Encapsulate common behavior.

-Separate high-level access decisions from presentation code.

-Apply wholesale changes to many different resources.

Steps to creating Filters

A filter implements the javax.servlet.Filter interface. The primary filter functionality is implemented by the doFilter() method of the filter.

1. Create class that implements Filter ifnterace.

– Methods: doFilter, init, destroy

void init(FilterConfig config) throws ServletException: Called before the filter goes into service, and sets the filter’s configuration object

void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException: Performs the actual filtering work.

– first two arguments are of type ServletRequest and ServletResponse, not HttpServletRequest and HttpServletResponse. Do a typecast if you need HTTP-specific capabilities

-final argument is a FilterChain, not a Filter. Its doFilter method is different – two arguments only.

void destroy(): Called after the filter has been taken out of service

2. Put filtering behavior in doFilter.

– Args: ServletRequest, ServletResponse, FilterChain
3. Call doFilter method of the FilterChain.

– This invokes next filter (if any) or actual resource
4. Register the filter with the appropriate servlets and JSP pages.

– Use filter and filter-mapping in web.xml.

To use a filter, you can declare it in the web.xml deployment descriptor using the <filter> tag, as shown below:

This notifies the server that a filter named testFilter is implemented in the TestFilter class. You can apply a registered filter to certain URL patterns or servlet names using the <filter-mapping> tag:

Or you can use annotation in filter class such as:
@WebFilter(filterName = "testFilter", urlPatterns = {"*.jsp"})

Filter API

The javax.servlet package contains the three interfaces of Filter API.

Filter

FilterChain

FilterConfig

1. Filter interface

Filter interface provides the life cycle methods for a filter.

public void init(FilterConfig config):

public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain):

public void destroy():

2. FilterChain interface

This interface is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter method of Filter interface.The FilterChain interface contains only one method:

public void doFilter(ServletRequest request, ServletResponse response): it passes the control to the next filter or resource.

3. FilterConfig interfac

The FilterConfig interface declares four methods:

public String getFilterName(): -obtains the textual name of the filter, as defined in the web.xml deployment descriptor.

public String getInitParameter(String paramName): – obtains the string value of a specific initialization parameter by name. Returns null if not found.

public Enumeration getInitParameterNames(): -obtains a java.util.Enumeration consisting of all the names of the initialization parameters for this instance.

public ServletContext getServletContext(): -obtains the ServletContext that the filter is executing within.

Simple Example

index.jsp

filters/SimpleFilter.java

web.xml

This filter example simply displays information about the invoking of the filter after the processing of the request of index page.

Show more