Servlet.init() and Filter.init() call sequence

时光总嘲笑我的痴心妄想 提交于 2019-12-20 08:56:48

问题


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?


回答1:


The filters are always initialized during webapp's startup in the order as they are defined in the 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>
    <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 after the initialization of filters, but before invocation of the filters.




回答2:


  1. For all filters: Filter.init()
  2. For all servlets with '' in web.xml: Servlet.init()
  3. For all applicable filters for request: Filter.doFilter()
  4. If applicable servlet not already initialised: Servlet.init()
  5. For applicable servlet: Servlet.service()



回答3:


Just a side note - I experienced on tomcat (7.0.30) that the Filter.init() methods are run in random order (iteration over HashMap).




回答4:


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.



来源:https://stackoverflow.com/questions/2906344/servlet-init-and-filter-init-call-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!