Servlet filtering


 

+

Search Tips   |   Advanced Search

 

Servlet filtering transforms request and responses.

We can chain filters together.

Filter types...

Filter life cycle is similar to servlets...

  1. Web container determines whether it needs to construct a FilterChain containing the LoggingFilter for the requested resource.

    The FilterChain begins with the invocation of the LoggingFilter and ends with the invocation of the requested resource.

  2. If other filters need to go in the chain, the Web container places them after the LoggingFilter and before the requested resource.

  3. The Web container instantiates the LoggingFilter and invokes the method...

    doFilter(FilterConfig)

  4. The LoggingFilter preprocesses the request and response objects and invokes the filter chain method...

    doFilter(ServletRequest, ServletResponse)

    This method passes the processing to the next resource in the chain, the requested resource.

  5. Upon return from the filter chain method...

    doFilter(ServletRequest, ServletResponse)

    ...the LoggingFilter performs post-processing on the request and response object before sending the response back to the client.

For transitioning users: Servlet 2.4 allows a new <dispatcher> element in the deployment descriptor with possible values...

REQUEST, FORWARD, INCLUDE, ERROR

...instead of invoking filters with RequestDispatcher.

For example:

    
<filter-mapping>
    <filter-name>Logging Filter</filter-name>
    <url-pattern>/products/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

This indicates that the filter should be applied to requests directly from the client as well as forward requests. Adding the INCLUDE and ERROR values also indicates that the filter should additionally be applied for included requests and <error-page> requests.

If we do not specify any <dispatcher> elements, then the default is REQUEST.

 

Filter, FilterChain, FilterConfig classes for servlet filtering

The following interfaces are defined as part of the javax.servlet package:

Interface Methods
Filter doFilter, getFilterConfig, setFilterConfig
FilterChain doFilter
FilterConfig getFilterName, getInitParameter, getInitParameterNames, getServletContext

The following classes are defined as part of the javax.servlet.http package:





 

Related

Web apps: Links

 

Related information

Servlet 2.4 specification