10

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

Community
  • 1
  • 1
Timofei Davydik
  • 7,244
  • 7
  • 33
  • 59
  • 5
    You are looking for something called "ServletContextListener", it has methods you need. – Harry Joy Dec 11 '12 at 11:51
  • See https://stackoverflow.com/questions/3468150/using-special-auto-start-servlet-to-initialize-on-startup-and-share-application – rogerdpack Jan 18 '18 at 22:12

1 Answers1

33

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>
Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
Abubakkar
  • 15,488
  • 8
  • 55
  • 83
  • 4
    Look into the @WebListener annotation also. – theglauber Apr 07 '14 at 17:30
  • I needed this and it works. There is also the "load-on-startup" way of doing this. My problem is that both methods initialize the class twice. Any idea? I saw this issue here http://stackoverflow.com/questions/7301088/tomcat-servlet-init-called-twice-upon-startup. I just cant understand what to do. Not very familiar with Java. – Harlan Gray Nov 23 '16 at 06:04
  • Thank you it very useful – Lova Chittumuri Jun 04 '17 at 13:18
  • What if my `` is `org.springframework.web.context.ContextLoaderListener` ? Which method will my tomcat server recall first? I mean, which is the entrypoint of my application? – andreagalle Feb 03 '22 at 15:04