Servlets run in a web container, and the main method of a web container goes out of your control.
If you want to perform any startup operations, the servlet structure provides context listeners that can be registered within the framework. These lsteners are called when the web application starts.
Alternatively, if you want to perform some operation for each incoming request or outgoing response, you can use servlet filters
source share