Can load-on-startup in web.xml be used to load an arbitrary class on startup?
Those are meant to specify the loading order for servlets. However, servlets are more meant to control, preprocess and/or postprocess HTTP requests/responses while you sound like to be more looking for a hook on webapp's startup. In that case, you rather want a ServletContextListener
.
@WebListener
public class Config implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
// Do your thing during webapp's startup.
}
public void contextDestroyed(ServletContextEvent event) {
// Do your thing during webapp's shutdown.
}
}
If you're not on Servlet 3.0 yet (and thus can't use @WebListener
), then you need to manually register it in web.xml
as follows:
<listener>
<listener-class>com.example.Config</listener-class>
</listener>
See also:
- Servletcontainer lifecycle
The element load-on-startup indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the Web application. The element content of this element must be an integer indicating the order in which the servlet should be loaded.In other words, container loads the servlets in ascending integer value. The 0 value will be loaded first then 1, 2, 3 and so on.
Let's try to understand it by the example given below:
web.xml
<web-app>
....
//=====================servlet 1==============
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>com.javatpoint.FirstServlet</servlet-class>
<load-on-startup>0</load-on-startup> //value given 0(zero)
</servlet>
//=====================servlet 2==============
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>com.javatpoint.SecondServlet</servlet-class>
<load-on-startup>1</load-on-startup> //value given 1(one)
</servlet>
...
</web-app>
There are defined 2 servlets, both servlets will be loaded at the time of project deployment or server start. But, servlet1 will be loaded first then servlet2.
Passing negative value : If you pass the negative value, servlet will be loaded at request time, at first request.