2

The reason I'm asking this is that I want to write code that initializes the application once it starts and cleans up later on.

I dont want to use a servlet init() method since it is per servlet.

jmj
  • 237,923
  • 42
  • 401
  • 438
Basil Musa
  • 8,198
  • 6
  • 64
  • 63

2 Answers2

8

There is no main() method in Servlet.

If

The reason I'm asking this is that I want to write code that initializes the application once it starts and cleans up later on.

You can use ServletContextListener implemented

public class MyServletContext implements ServletContextListener{
    ServletContext context;
    public void contextInitialized(ServletContextEvent contextEvent) {
        System.out.println("Context Created");

    }
    public void contextDestroyed(ServletContextEvent contextEvent) {

        System.out.println("Context Destroyed");
    }
}

web.xml

<listener>
    <listener-class>
        com.yourpackage.MyServletContext
    </listener-class>
  </listener>
jmj
  • 237,923
  • 42
  • 401
  • 438
4

There is no main() method, because the components are managed and the container invokes other methods - like the init() on servlets and filters. The container itself is started through a main method, but even that's hidden from you.

For per-application and initialization you can use a ServletContextListener

You have to map it in web.xml using <listener><listener-class>...</listener-class></listener>. In contextInitialized(..) and contextDestroyed(..) you can do initialization and cleanup respectively.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140