Servlet filtering is an integral part of the Servlet 2.3 API. Servlet filtering provides a new type of object called a filter that can transform a request or modify a response.
You can chain filters together so that a group of filters can act on the input and output of a specified resource or group of resources.
Filters typically include logging filters, image conversion filters, encryption filters, and Multipurpose Internet Mail Extensions (MIME) type filters (functionally equivalent to the servlet chaining). Although filters are not servlets, their lifecycle is very similar.
Filters are handled in the following manner...
- The Web container determines whether it needs to construct a FilterChain containing the LoggingFilter for the requested resource.
- If other filters need to go in the chain, the Web container places them after the LoggingFilter and before the requested resource.
- The Web container then instantiates and initializes the LoggingFilter (if it was not done previously) and invokes its doFilter(FilterConfig) method to start the chain.
- The LoggingFilter preprocesses the request and response objects and then invokes the filter chain doFilter(ServletRequest, ServletResponse) method.
This method passes the processing to the next resource in the chain (in this case, the requested resource).
- Upon return from the filter chain doFilter(ServletRequest, ServletResponse) method, the LoggingFilter performs post-processing on the request and response object before sending the response back to the client.
See AlsoFilter, FilterChain, FilterConfig classes for servlet filtering
Webapplications: Resources for learning