Start a Servlet automatically at startup

You can have a servlet automatically startup when the Tomcat (or other) server starts. This is useful for example in case you would like to start a connection pool servlet. Modify the web.xml file that describes your servlet and include a tag called load-on-startup. The contents of this tag must be a positive integer indicating the order in which the servlet should be loaded. Lower integers are loaded before higher integers. For example:

<web-app>
    <servlet>
        <servlet-name> HelloWorldServlet </servlet-name>
        <servlet-class> HelloWorldServlet </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
</web-app>

Start up your server and check the logs. In Tomcat, logs/servlet.log shows a call the the init method that you can override in your servlet:

2001-03-19 11:27:10 - path="/examples" :jsp: init
2001-03-19 11:27:10 - path="/helloworld" :jsp: init
2001-03-19 11:27:10 - path="/helloworld" :HelloWorldServlet: init
2001-03-19 11:27:10 - path="/admin" :jsp: init