How to run specific java code on Tomcat start or on application deploy?
java, servlets, tomcat
Solution
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>
Problem
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
Related problems
- Using special auto start servlet to initialize on startup and share application data
- tomcat auto start servlet
- How do I load a java class (not a servlet) when the tomcat server starts
- Tomcat - Servlet init() called twice upon startup
- tomcat auto start servlet
- How do I load a java class (not a servlet) when the tomcat server starts