除了在 web.xml 中声明之外,还有什么方法可以指定过滤器的顺序吗?

Is there any way to specify the order of a filter outside of declaring it in web.xml?

从 Servlet 3.0 开始,我们现在可以通过注释(@WebFilter)or dynamically (via the ServletContext 对象)声明 Web 过滤器。

我知道使用@WebFilter 不允许指定过滤器顺序。同样,在通过 ServletContext.addFilter() 方法动态声明顺序时,我还没有找到任何指定顺序的方法。我查看了 FilterRegistration 对象,但也没有任何内容。

这是否意味着在过滤器链中指定过滤器顺序的唯一方法是通过 web.xml?没有其他可用的机制吗?这不是对 Servlet 3.0+ 的重大疏忽吗?

通过注释或通过 ServletContext 对象声明的过滤器在链中的哪个位置?在 web.xml 中声明的末尾?未定义?

Does that mean that the only way to specify the order of a filter in the filter chain is via web.xml?

是的。检查 Servlet 3.0 spec 的以下部分:

  • 4.4.2 以编程方式添加和配置过滤器

  • 6.2.4 Web 应用程序中过滤器的配置

  • 8.1.2 @WebFilter

唯一提到过滤器排序的地方是在第 6.2.4 节中,它指定了如何使用 web.xml 进行排序。 addFilter()@WebFilter.

部分未提及排序

Is there no other mechanism available?

Servlet 3.0 规范中没有,所以没有。

Is this not a significant oversight of Servlet 3.0+?

我怀疑遗漏是 "oversight"。 BalusC 的评论是 relevant SO post 提供了一个没有替代机制的合理原因:如果您的 webapp 附带包含过滤器的第 3 方库怎么办?很难事先说出它的顺序。

Where in the chain do filters declared via annotation or via the ServletContext object? At the end of those declared in web.xml? Undefined?

顺序必然未定义,因为规范未解决这些情况。