Possible Duplicate:
tomcat auto start servlet
How do I load a java class (not a servlet) when the tomcat server starts
I have web application running on Tomcat server. I want to run specific code in my application once when Tomcat starts or when this application is deployed. How can I achieve it? Thanks
You need to implement ServletContextListner interface and write the code in it that you want to execute on tomcat start up.
Here is a brief description about it.
ServletContextListner is inside javax.servlet package.
Here is a brief code on how to do it.
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
//Notification that the servlet context is about to be shut down.
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
// do all the tasks that you need to perform just after the server starts
//Notification that the web application initialization process is starting
}
}
And you need configure it in your deployment descriptor web.xml
<listener>
<listener-class>
mypackage.MyServletContextListener
</listener-class>
</listener>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With