I have a java EE program for the backend of a web application. It runs in a tomcat server. While I am able to make classes to setup routing, etc, how would I make a class that doesn't affect routing that also runs on launch? I want to make a class that connects to a database. This would need to happen regardless of whether a web-page is requested or not. I made a class for it with a
public static void main (String [] args)
, but how would I make this run when I launch the application? I don't understand what class is called on launch. I have the web.xml and all the classes that control routing, but is there a main class I can use to call this? If not, how do I call the class to run at the same time as the server starts?

- 13
- 1
- 5
4 Answers
(1) Prepare a class that implements javax.servlet.ServletContextListener
.
(2) Write your start-up code in contextInitialized(ServletContextEvent event)
method of the class.
(3) Register the class in web.xml like the following.
<listener>
<listener-class>com.example.YourServletContextListener</listener-class>
</listener>
This can initialize your application without servlet invocation.

- 18,118
- 9
- 62
- 105
In your servlet init() method you can perform all your initializing tasks ( i.e task you need to perform when you load your application). Also note in the web.xml deployment file make load-on-startup value as 1 to indicate to container to load the servlet immediately and call its init() method.

- 712
- 6
- 9
You should not use a main method in web applications. Instead you can move the code from main method to the constructor of that class or Create a new public method in that class.
Then Orveride the Init Method in your servlet to Create an instance of the Class and invoke the method.
Servlet Init is invoked only once (usually) when the servlet is accessed for the first time Or when server is booted up.
This would mean that your class is invoked only once during the loading of the servlets.

- 880
- 13
- 25
What about a startup EJB Singleton?
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
@Startup
@Singleton
public class StartUpService {
@PostConstruct
public void start() {
// what you want to execute at startup
}
}

- 1,568
- 2
- 24
- 34