How to Run a Code Immediately After the Web Application or Context is Deployed in Tomcat
If are writing a web app using Java (JSP or Servlets), sometime we want to execute a code section immediately after the application context has deployed. For examples to:
- Initialize Caching system
- Initialize some scheduling services
- Put some data is application scope that will be needed frequently.
- Make a class MyListener that implements ServletContextListener
- Write the code you want to run only once (after the context is loaded, i.e. when the web application is deployed in Tomcat) in contextInitialized(ServletContextEvent cse) method.
package mypackage;After you have done it. Configure you Listener in web.xml like this:
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent cse) {
//write you code here ...
}
public void contextDestroyed(ServletContextEvent cse) {
// write java code here that you want to run after the context is destroyed.
}
}
Please note that, the code written in Listener classes run even before the run-on-startup Servlets. And if need to write multiple Listener. Make sure you put then in right order. The Listeners are executed in the order they are configured.
mypackage.MyListener
Comments
Post a Comment