How does the filter chain work?

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

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

I’m interested to know behind the scenes in the container how the container handles the filter chain. Can anyone explain how the filter chain inside the container is handled?

+6
source share
1 answer

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

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

enter image description here

1. Requires a servlet target. container detects two filters and creates a filter chain .

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

3. The first filter completes any preprocessing, then calls the doFilter() filter chain method. This causes the second filter called by the doFilter() method.

4. The second filter completes any preprocessing, then calls the doFilter() filter chain method. This causes the target servlet called by its service() method.

5. When the servlet target is completed, the doFilter() chain call in the second filter returned, and the second filter can do any post-processing.

6. When the second filter complete, the doFilter() chain calls the first filter returns, and the first filter can do any post-processing.

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

Filters can be placed between servlets and the servlet container for wrapping and preprocesses, or for wrapping and postprocesses. None of the filters are aware of their order. The order is processed completely through the filter chain in accordance with the order in which the filters are configured in web.xml

+15
source

Source: https://habr.com/ru/post/973523/


All Articles