I was using WebSphere Application Server, and it gives a platform initialization listener which is invoked when an app gets started. Now, I am using Apache Tomcat, but have not found such stuff, and what I'm trying to do is do some initialization work before the application begins to serve requests.
How should I do it by Apache Tomcat?
You create a Listener class what implement ServletContextListener like this:
package com.vy;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class StartStopListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("Servlet has been started.");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("Servlet has been stopped.");
}
}
Add configuration information to WEB-INF\web.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<listener>
<listener-class>com.vy.StartStopListener</listener-class>
</listener>
</web-app>
When run Tomcat, You will see result at console screen:
Servlet has been started.
Reference: http://docs.oracle.com/javaee/7/api/javax/servlet/ServletContextListener.html
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