call method on server startup

user1438082 picture user1438082 · Mar 24, 2013 · Viewed 15.3k times · Source

I am trying to call a method when my webapplication starts. The purpose is to kick-off a timer that does some work at defined intervals. how do i call a function helloworld when my jboss 7.1 web application starts up?

Answer

Karthik Rajah picture Karthik Rajah · Mar 24, 2013

If you want to run some code before your web app serves any of your clients you need a ServletContextListener.

Create your listener class

import javax.servlet.*;

public class MyServletContextListener implements ServletContextListener {

 public void contextInitialized(ServletContextEvent e) {
   //Call your function from the event object here
 }

 public void contextDestroyed(ServletContextEvent e) {

 }
}

Put the class in WEB-INF/classes

Put a <listener> element in the web.xml file.

<listener>
  <listener-class>
     com.test.MyServletContextListener
  </listener-class>
</listener>

Hope this helps.