java Servlet.init() 和 Filter.init() 调用顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2906344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Servlet.init() and Filter.init() call sequence
提问by martsraits
In which order are Servlet.init() and Filter.init() methods called in java web application? Which one is called first? Are all Servlet.init() methods called before than any Filter.doFilter method?
java web 应用程序中 Servlet.init() 和 Filter.init() 方法的调用顺序是什么?先调用哪个?是否所有 Servlet.init() 方法都比任何 Filter.doFilter 方法更早调用?
采纳答案by BalusC
The filters are always initialized during webapp's startup in the order as they are defined in the web.xml.
过滤器总是在 webapp 启动期间按照它们在web.xml.
The servlets are by default initialized during the first HTTP request on their url-pattern only. But you can configure them as well to initialize during webapp's startup using the <load-on-startup>entries wherein you can specify their priority. They will then be loaded in the priority order.
E.g.
默认情况下,servlet 仅在其 url-pattern 上的第一个 HTTP 请求期间初始化。但是您也可以将它们配置为在 webapp 启动期间使用<load-on-startup>可以指定其优先级的条目进行初始化。然后它们将按优先级顺序加载。
例如
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>mypackage.MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
If there are more servlets with the same priority order, then the loading order for those servlets is unspecified and may be arbitrary. Servlets are however in any way initialized afterthe initialization of filters, but beforeinvocation of the filters.
如果有更多具有相同优先级顺序的 servlet,则这些 servlet 的加载顺序是未指定的并且可能是任意的。然而,在过滤器初始化之后,但在过滤器调用之前,servlet 以任何方式被初始化。
回答by Tendayi Mawushe
- For all filters:
Filter.init() - For all servlets with '' in
web.xml:Servlet.init() - For all applicable filters for request:
Filter.doFilter() - If applicable servlet not already initialised:
Servlet.init() - For applicable servlet:
Servlet.service()
- 对于所有过滤器:
Filter.init() - 对于所有带有 '' in 的 servlet
web.xml:Servlet.init() - 对于所有适用的请求过滤器:
Filter.doFilter() - 如果适用的 servlet 尚未初始化:
Servlet.init() - 对于适用的 servlet:
Servlet.service()
回答by Jan Gutvirth
Just a side note - I experienced on tomcat (7.0.30) that the Filter.init() methods are run in random order (iteration over HashMap).
只是一个旁注 - 我在 tomcat (7.0.30) 上体验到 Filter.init() 方法以随机顺序运行(通过 HashMap 迭代)。
回答by mkhludnev
Beware. I've been witnessing concurrent invocation of Filter.init() and Filter.doFilter() on the same instance. I'm still shocked and can't recover. Its' name is Jetty.
谨防。我一直在见证 Filter.init() 和 Filter.doFilter() 在同一个实例上的并发调用。我仍然震惊,无法恢复。它的名字是码头。

