While the accepted answer by Crazy Ninja is correct, there is an alternative.
ServletContextListener
The Servlet spec defines the ServletContextListener
interface for you to define a class to be instantiated and invoked:
- Before any of your servlets (and filters) begin executing, and…
- After the last of your servlets (and filters) have finished executing because your web app is being shutdown.
Your class implementing the ServletContextListener
is invoked whenever the web app (the “context”) has been initialized by the Servlet container.
Some Servlet containers automatically initialize their contexts when launched. So your initialization code place here may execute long before your first user hits the server. Whenever your container chooses to initialize your web app (context), rest assured that the Servlet spec guarantees that any container runs, and finishes running, your context listener before handling the first call to your servlets/filters.
I just happened to post a Question/Answer pair on this topic, Hook for my Vaadin web app starting and stopping?. See that page for much more discussion.