How filter chain invocation works?

前端 未结 1 611
后悔当初
后悔当初 2021-02-03 10:43

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.d

相关标签:
1条回答
  • 2021-02-03 11:00

    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:

    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

    0 讨论(0)
提交回复
热议问题