How filter chain invocation works?

Abhijeet Panwar picture Abhijeet Panwar · Aug 8, 2014 · Viewed 11.8k times · Source

I am trying to understand filter chaining.As defined in this question

All filters are chained (in the order of their definition in web.xml). The chain.doFilter() is proceeding to the next element in the chain. The last element of the chain is the target resource/servlet.

I am interested to know behind the scene in container that how container handles filter chaining.Can someone explain that how Filter chaining is handled inside container?

Answer

SparkOn picture SparkOn · Aug 8, 2014

Each filter implements the javax.servlet.Filter interface, which includes a doFilter() method that takes as input a request and response pair along with a filter chain, which is an instance of a class (provided by the servlet container) that implements the javax.servlet.FilterChain interface. The filter chain reflects the order of the filters. The servlet container, based on the configuration order in the web.xml file, constructs the chain of filters for any servlet or other resource that has filters mapped to it. For each filter in the chain, the filter chain object passed to it represents the remaining filters to be called, in order, followed by the target servlet.

If there are two filters, for example, the key steps of this mechanism would be as follows:

enter image description here

1.The target servlet is requested. The container detects that there are two filters and creates the filter chain.

2.The first filter in the chain is invoked by its doFilter() method.

3.The first filter completes any preprocessing, then calls the doFilter() method of the filter chain. This results in the second filter being invoked by its doFilter() method.

4.The second filter completes any preprocessing, then calls the doFilter() method of the filter chain. This results in the target servlet being invoked by its service() method.

5.When the target servlet is finished, the chain doFilter() call in the second filter returns, and the second filter can do any postprocessing.

6.When the second filter is finished, the chain doFilter() call in the first filter returns, and the first filter can do any postprocessing.

7.When the first filter is finished, execution is complete.

Filters can be interposed between servlets and the servlet container to wrap and preprocess requests or to wrap and postprocess responses. None of the filters are aware of their order. Ordering is handled entirely through the filter chain, according to the order in which filters are configured in web.xml