分两步走:
(1)实现 javax.servlet.ServletContextListener
接口的两个方法:contextInitialized()和contextDestroyed()
contextInitialized():当Servlet容器启动时会执行contextDestroyed():当Servlet容器停止时会执行
(2)在contextInitialized()中加入需要监听的程序,并由 java.util.Timer 的
schedule() 方法来控制监听程序执行的频率
DEMO(这是我的监听的程序原型)
package com.company.servlet;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.company.task.ClearApplicationAttributeTask;
public class TaskListener implements ServletContextListener {
private static Timer timer = null;
private static ClearApplicationAttributeTask caaTask = null;
public void contextDestroyed(ServletContextEvent arg0) {
//终止此计时器,丢弃所有当前已安排的任务
if(timer != null)
timer.cancel();
}
public void contextInitialized(ServletContextEvent arg0) {
caaTask = new ClearApplicationAttributeTask(arg0.getServletContext());
timer = new Timer(true);
// 定义任务时间,每天0时执行
GregorianCalendar now = new GregorianCalendar();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
timer.schedule(caaTask, now.getTime());
}
}
package com.company.task;
import java.util.TimerTask;
import javax.servlet.ServletContext;
public class ClearApplicationAttributeTask extends TimerTask {
private ServletContext context = null;
public ClearApplicationAttributeTask(ServletContext sc)
{
this.context = sc;
}
public void run()
{
// 在这里可以做一些想做的事情,比如清空application中的属性
context.removeAttribute("app_name");
}
}
将编译好的class文件放入WEB-INF/classes中,最后别忘记了在Servlet容器中当前WEB应用的web.xml中加入监听语句:
<listener>
<listener-class>com.company.servlet.TaskListener</listener-class>
</listener>