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

后端 未结 4 820
旧时难觅i
旧时难觅i 2020-12-28 17:45

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

4条回答
  •  我在风中等你
    2020-12-28 18:25

    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:

    
        com.example.Config
    
    

    See also:

    • Servletcontainer lifecycle

提交回复
热议问题