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?
Each filter implements the
javax.servlet.Filter
interface, which includes adoFilter()
method that takes as input arequest
andresponse
pair along with a filter chain
, which is an instance of a class (provided by the servlet container) that implements thejavax.servlet.FilterChain
interface. The filter chain reflects the order of the filters.The servlet container
, based on the configuration order in theweb.xml
file, constructs the chain offilters
for anyservlet
or other resource that hasfilters
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:1.The target
servlet
is requested. Thecontainer
detects that there are twofilters
and creates thefilter chain
.2.The first
filter
in the chain is invoked by itsdoFilter()
method.3.The first
filter
completes any preprocessing, then calls thedoFilter()
method of thefilter chain
. This results in the secondfilter
being invoked by itsdoFilter()
method.4.The second
filter
completes any preprocessing, then calls thedoFilter()
method of thefilter chain
. This results in the targetservlet
being invoked by itsservice()
method.5.When the target
servlet
is finished, the chaindoFilter()
call in the secondfilter
returns, and the secondfilter
can do any postprocessing.6.When the second
filter
is finished, the chaindoFilter()
call in the firstfilter
returns, and the firstfilter
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