ContextListener的基本知识

本文介绍如何在Tomcat启动和关闭时执行特定任务,如覆盖率数据写入等。通过实现`ServletContextListener`接口并覆盖`contextInitialized`及`contextDestroyed`方法,在web.xml文件中配置监听器来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多时候我们都需要在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) {
    }
  }


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值