How can I load an arbitrary class on startup in Tomcat?
I saw load-on-startup
tag for web.xml
file, but can I use it and how should I implement my class?
<servlet-name>??</servlet-name>
<servlet-class>??</servlet-class>
<load-on-startup>10</load-on-startup>
The load-on-startup element of web-app loads the servlet at the time of deployment or server start if value is positive. It is also known as pre initialization of servlet. You can pass positive and negative value for the servlet.
The <load-on-startup> element indicates that the servlet should be loaded on the startup of the web application. The optional contents of this element must be a positive integer that specifies the order in which the servlet should be loaded. Servlets with lower values are loaded before servlets with higher values.
The element content of 'load-on-startup' is Integer. if the integer is negative: The container loads servlet at any time. if the integer is 0 or positive: The servlet marked with lower integers are loaded before servlets marked with higher integers.
init-param This is an element within the servlet. The optional init-param element contains a name/value pair as an initialization attribute of the servlet. Use a separate set of init-param tags for each attribute.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With