Can load-on-startup in web.xml be used to load an arbitrary class on startup?

enfix picture enfix · Jul 20, 2010 · Viewed 25.6k times · Source

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>

Answer

BalusC picture BalusC · Jul 20, 2010

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: