很多时候我们都需要在tomcat启动的时候做一些事情,或者在tomcat停止的时候也做一些事情.(比如覆盖率数据的写入.)
Object
|
Event
|
Listener Interface and Event Class
|
---|---|---|
Web context
(see Accessing the Web Context ) |
Initialization and destruction
| |
Attribute added, removed, or replaced
| ||
Session
(See Maintaining Client State ) |
Creation, invalidation, activation, passivation, and timeout
| |
Attribute added, removed, or replaced
| ||
Request
|
A servlet request has started being processed by web components
| |
Attribute added, removed, or replaced
|
//在web.xml中配置listener
//这样tomcat启动的时候会跑contextInitialized.
//tomcat停止的时候会跑contextDestroyed.
import javax.servlet.*;
import util.Counter;
public final class ContextListener
implements ServletContextListener {
private ServletContext context = null;
public void contextInitialized(ServletContextEvent event) {
context = event.getServletContext();
...
}
public void contextDestroyed(ServletContextEvent event) {
// cobertura写入测试数据.
try {
String className = "net.sourceforge.cobertura.coveragedata.ProjectData";
String methodName = "saveGlobalProjectData";
Class saveClass = Class.forName(className);
java.lang.reflect.Method saveMethod = saveClass.getDeclaredMethod(methodName, new Class[0]);
saveMethod.invoke(null,new Object[0]);
} catch (Throwable t) {
}
}