Servlet.init() and Filter.init() call sequence
- For all filters:
Filter.init()
- For all servlets with
<load-on-startup>
inweb.xml
:Servlet.init()
- For all applicable filters for request:
Filter.doFilter()
- If applicable servlet not already initialised:
Servlet.init()
- For applicable servlet:
Servlet.service()
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.
Just a side note - I experienced on tomcat (7.0.30) that the Filter.init() methods are run in random order (iteration over HashMap).