How filter chain invocation works?

本小妞迷上赌 提交于 2020-04-07 14:18:42

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/25196867/how-filter-chain-invocation-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!