Filter

Filters are Java components similar to servlets that are used to filter the connection between client and servlets.

To create a filter we implements the Filter interface, specifying what it should do in the doFilter() method.

In the DD we could declare the filter (if we don't use the annotations that are now available) and we map the filter with the resources we want they want to interact with.

Let's see an example where the filter simply log the user name (when available) for any request sent to a servlet named with the extension ".do".

The class implementation:
package ch13;

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.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;

@WebFilter( filterName = "BeerRequest",
description = "log the caller",
urlPatterns = { "/BeerReqFilter" })
public class BeerReqFilter implements Filter {
    private FilterConfig fc;

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

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
        String name = ((HttpServletRequest)request).getRemoteUser();
        if(name != null) {
            fc.getServletContext().log("User: " + name + " is updating");
        }
        else {
            fc.getServletContext().log("Remote user name not available");
        }

        // pass the request along the filter chain
        chain.doFilter(request, response);
    }

    public void destroy() {
    }
}
The doFilter() accepts Servlet Request and Response as parameter, we normally have to downcast them to the appropriate Http subclass in the method body.

At the end of the job, we pass explicitely the control to the next filter (or servlet) in the chain.

If we need, we could specify init parameters for the filter using the initParams attribute. For example, if we want to use a special log file, we can set it in this way:
initParams = @WebInitParam(name="LogFileName", value="UserLog.txt")
In the DD we specify when the filter should be used, like this:
<filter-mapping>
<filter-name>BeerRequest</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
Filters are discussed in chapter twelve of Head First Servlet and JSP.

No comments:

Post a Comment