What is chain.doFilter doing in Filter.doFilter method?

后端 未结 6 1916
予麋鹿
予麋鹿 2020-12-08 06:51

In a Filter.doFilter method I made this call chain.doFilter.

What is doFilter doing inside a doFilter? Isn\'t it a recursive call?

相关标签:
6条回答
  • 2020-12-08 06:58

    By calling chain.doFilter you are handing the request/response to the next filter in your filter chain. If you do not call it then the next filter (probably defined in your web.xml) will not be executed.

    If you just called doFilter, then yes you would have endless recursion and a stackoverflow. However, you are calling the doFilter method of the filterChain object, which instructs it to execute the next filter.

    0 讨论(0)
  • 2020-12-08 07:05

    Servlet Filters are an implementation of the Chain of responsibility design pattern.

    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.

    0 讨论(0)
  • 2020-12-08 07:06

    Internally it invokes doFilter of the next filter in the filter chain, and, when chain is over, it invokes the target servlet.

    0 讨论(0)
  • 2020-12-08 07:14

    Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.

    0 讨论(0)
  • 2020-12-08 07:17

    Not having any code that you are talking about, I can only assume that you something like:

    class Filter implements FilterAPI {
      private FilterAPI chain;
      FilterAPI(FilterAPI chain) { this.chain = chain; }
      @override void doFilter (Set setToFilter) {
        // do some filtering on setToFilter
        chain.doFilter(setToFilter);
      }
    }
    

    If that is the case, then you are not calling anything recursively, you are calling doFilter() on a different object. As mentioned on an another answer, this is the well known Chain of Responsibility design pattern.

    0 讨论(0)
  • 2020-12-08 07:22

    It is calling the doFilter method of the chain object, not itself, so no, it won't be recursive.

    The name chain suggests that you have a sequence of filters, with each filter doing some processing and then passing on to the next in sequence, so each object has a chain member to point to the next filter in the sequence, which gets called after the filter has performed its own processing. The last in the sequence will then probably have null as the chain value, or it knows on its own that it is the last one in the sequence.

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