to the main page about the tutorial  INTERACTIVE WEB SERVICES WITH JAVA back up next

Filters

- inserting hooks before and after requests are processed
- wrappers modify the request and the response

A Filter can modify

FilterChain: multiple filters are processed in deployment order in a stack discipline with the Servlet in the bottom.

Supplementary, HttpServletRequestWrapper and HttpServletResponseWrapper provide wrappers to modify the request/response.

Example filter and deployment declaration:
public class TraceFilter implements Filter 
{
    private ServletContext context;

    public void init(FilterConfig config)
        throws ServletException
    {
        context = config.getServletContext();
    }

    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException
    {
        context.log("["+request.getRemoteHost()+"] request: "+ 
                    ((HttpServletRequest) request).getRequestURL());
        chain.doFilter(request, response);
        context.log("["+request.getRemoteHost()+"] done");
    }
}

<filter>
  <filter-name>myfilter</filter-name>
  <filter-class>TraceFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>myfilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

back COPYRIGHT © 2002-2003 ANDERS MØLLER & MICHAEL I. SCHWARTZBACH next