tomcat auto start servlet

10,350

Solution 1

you could use the servlet context listener. More specifically you could start your thread in the contextInitialized method:

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
         // start the thread
    }

    public void contextDestroyed(ServletContextEvent sce) {
         // stop the thread
    }
}

then add:

<listener>
    <description>ServletContextListener</description>
    <listener-class>MyListener</listener-class>
</listener>

in you web.xml

Solution 2

Use the load-on-startup in WEB-INF/web.xml. In Netbeans it is in the Servlets tab, the item "Startup order".

<servlet>
    <servlet-name>Hl7Servlet</servlet-name>
    <servlet-class>nl.vandenzen.Hl7Servlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
Share:
10,350
user85116
Author by

user85116

Updated on June 27, 2022

Comments

  • user85116
    user85116 almost 2 years

    I have a standard GWT application, and it of course uses a Java servlet on the backend. This servlet is deployed on Tomcat and Windows Server.

    I know it's against the rules / suggestions, but I have one thread in this servlet that get's started when the servlet initializes (the "init" method of the servlet). The thread is a scheduler of sorts, its purpose is to perform different database tasks at certain times, totally independent of the GWT application / interface itself.

    What I need is for the servlet's "init" method to be called as soon as the war is deployed. Right now what I've been doing is, everytime there is an upgrade to the application, I drop the war into the right directory, then I have to "login" to the application GWT application so that its "init" method is called. I would like for the servlet's init method to be called as soon as the war is updated so that I don't have to login to the GWT application to do this.

    Any ideas?

  • user85116
    user85116 almost 15 years
    This is probably an effective solution, but right now I just need something as simple as possible, so that the least amount of changes to my code is necessary. But thanks anyways, I'll have to look into this in more detail in the future...
  • user85116
    user85116 almost 15 years
    Thank you, that's what I was looking for.
  • zg_spring
    zg_spring over 9 years
    yes, use load-on-startup can resolved it easily, and it acceptable to web servlet 2.4 or above.