Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run specific java code on Tomcat start or on application deploy? [duplicate]

Possible Duplicate:
tomcat auto start servlet
How do I load a java class (not a servlet) when the tomcat server starts

I have web application running on Tomcat server. I want to run specific code in my application once when Tomcat starts or when this application is deployed. How can I achieve it? Thanks

like image 685
Timofei Davydik Avatar asked Dec 11 '12 11:12

Timofei Davydik


1 Answers

You need to implement ServletContextListner interface and write the code in it that you want to execute on tomcat start up.

Here is a brief description about it.

ServletContextListner is inside javax.servlet package.

Here is a brief code on how to do it.

public class MyServletContextListener implements ServletContextListener {

  @Override
  public void contextDestroyed(ServletContextEvent arg0) {
    //Notification that the servlet context is about to be shut down.   
  }

  @Override
  public void contextInitialized(ServletContextEvent arg0) {
    // do all the tasks that you need to perform just after the server starts

    //Notification that the web application initialization process is starting
  }

}

And you need configure it in your deployment descriptor web.xml

<listener>
    <listener-class>
        mypackage.MyServletContextListener
    </listener-class>
</listener>
like image 119
Abubakkar Avatar answered Sep 28 '22 19:09

Abubakkar