How is the order of filters in
HttpSecurity maintained? I think many developers are interested in this issue. In this article, I will discuss this issue with you.
HttpSecurity contains a member variable
FilterOrderRegistration, this class is a built-in filter registry. As for the role of these filters, not the focus of this article, interested to see the
FilterOrderRegistration source code.
Built-in filter order
FilterOrderRegistration maintains a variable
filterToOrder that records the order between classes and the interval steps between the top and bottom. We copied a
FilterOrderRegistration to visualize the order of the filters.
We can see that the position between the built-in filters is relatively fixed, except for the first and second step of
200 and the other steps of
Built-in filters do not always take effect, they are simply prepositioned and need to be added explicitly via the
addFilterXXXXseries of methods in
Logic for registering filters
FilterOrderRegistration provides a
From this approach we can draw several conclusions.
- The built-in
34filters have a fixed serial number and cannot be changed.
- The class-qualified name of a newly added filter cannot be duplicated with the built-in filter.
- The order of the newly added filters can be duplicated with the order of the built-in filters.
gets the order value of registered filters
FilterOrderRegistration also provides a
HttpSecurity Methods for Maintaining Filters
Next we analyze a few of the ways in which
HttpSecurity maintains filters.
addFilterAtOffsetOf is a built-in private method of
Filter is the filter you want to register to the
offset is the offset to the right,
registeredFilter is the filter already registered to the
registeredFilter will cause a null pointer exception if it is not registered.
Always remember that
registeredFiltermust be a
Filterthat is registered in
addFilter series methods
Here is an example of
addFilterAfter is to place
filter one place after
afterFilter, if the order of
400, then the order of
addFilterAt logic and
addFilterAfter are only differences in offset values, so we won’t go over them here.
addFilter is special.
filter must be a
Filter that has been registered to
FilterOrderRegistration, which means it may be a built-in
Filter or a non-built-in
Filter that was previously registered with
Here comes the question
I saw a question earlier, if
HttpSecurity registers two
Filters with duplicate serial numbers, what will be the order? Let’s look at the ordering mechanism first.
After looking at the
OrderComparator source code, it is still sorted by the natural order of order numbers, the smaller the number, the higher it is. If the order numbers are the same, the smaller the index, the higher the order. That is, whoever
filters first is the first in the same order number ( the smaller the index of the first add to List ).