loulou
loulou

Reputation: 331

How to call a function while running a Java web application?

I have a web application in Java (Netbeans). And I have a function that should be called exactly while running the web application, without putting it into the static method main.

I really don't have any idea about how to do.

Thank you in advance.

Upvotes: 0

Views: 2446

Answers (1)

loulou
loulou

Reputation: 331

Create a class that implements ServletConextListener :

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

public class ListenToMeFirst implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // Run me First while deploying!!!

    }

}

Don't forget to put it in your web.xml file :

<listener>
  <listener-class>path.to.yourListenerClass.ListenToMeFirst</listener-class>
</listener>

Upvotes: 1

Related Questions