Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the main method of a WAR file?

Recently, I've reapackaged my java spring application to become a WAR file for deployment in tomcat. After some testing I noticed, that public static void main(String[] args) is not executed. Some necessary initialization of my application is done in main. Is there something like a main method in a WAR file? What is the appropiate place in a WAR file to run some initialization?

like image 475
user1785730 Avatar asked Apr 20 '15 12:04

user1785730


2 Answers

You can add a listener to your web.xml file:

<listener>
    <description>Application startup and shutdown events</description>
    <display-name>Test</display-name>
    <listener-class>com.package.package.StartClass</listener-class>
</listener>

public class StartClass implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
         //Context destroyed code here
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent)
    {
        //Context initialized code here
    }
}
like image 119
brso05 Avatar answered Jan 04 '23 16:01

brso05


Well, You will have to create a listener in your web.xml that will be invoked by container at the time of startup.

<listener>
    <listener-class>com.rdv.example.WebAppContext</listener-class>
</listener>

And this class will be implementing ServletContextListener

public class WebAppContext implements ServletContextListener {

public void contextInitialized(ServletContextEvent servletContextEvent) {
// Do your processing that you are trying to do in main method.
}
like image 30
Raja Avatar answered Jan 04 '23 18:01

Raja