Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tomcat auto start servlet [duplicate]

Tags:

tomcat

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?

like image 503
user85116 Avatar asked Apr 24 '09 13:04

user85116


2 Answers

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

like image 166
dfa Avatar answered Nov 09 '22 08:11

dfa


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>
like image 26
Carl van Denzen Avatar answered Nov 09 '22 08:11

Carl van Denzen