---
title: "使用ServletContextListener监听servlet容器"
author: "uule"
date: "2011-01-13T17:07:38Z"
tags: ["Servlet"]
categories: ["编程语言"]
slug: "servletcontextlistener-servlet"
draft: false
lastmod: "2017-07-14T13:41:35Z"
id: 870538
url: "https://uule.iteye.com/blog/870538"
---

实现 javax.servlet.ServletContextListener 接口  
当Servlet容器启动时会执行contextInitialized（）,当Servlet容器停止时会执行contextDestroyed（）  
在contextInitialized（）中加入需要监听的程序

 

```
/**
 * 定时器启动监听器
 */
public class TimerStartListener implements ServletContextListener {

	protected static final Logger logger = Logger
			.getLogger(TimerStartListener.class);


	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		TaobaoOrderTimerUtils taobaoOrderTimerUtils = SpringContextHolder
				.getBean("taobaoOrderTimerUtils");
		TimerUtils timerUtils = SpringContextHolder.getBean("timerUtils");
		sce.getServletContext().setAttribute("timerUtils", timerUtils);
		ITaoBaoStoreManager storeManager = SpringContextHolder
				.getBean("taoBaoStoreManager");
		List<TaoBaoStore> stores = new ArrayList<TaoBaoStore>();
		try {
			stores = storeManager.getAllTaoBaoStore();
		} catch (DBRuntimeException e) {
			logger.info("如果本次错误在首次安装出现，请忽略本异常！", e);
		}
		for (TaoBaoStore store : stores) {
			// 如果定时器为开启状态的在启动时开启定时任务
			if (store.getStatus_time_task() == 1) {
				taobaoOrderTimerUtils.startTimer(store);
			}
		}
	}
}
```

 项目中用到的！

 

**spring包中ContextLoaderListener**  
**servlet包中ServletContextListener**

 

===========================================================

**ServletRequestListener**用于**监听用户请求的到达**，实现该接口的监听器需要实现如下两个方法。

requestInitialized(ServletRequestEvent sre)：用户请求到底、被初始化时触发该方法。

requestDestroyed(ServletRequestEvent sre)：用户请求结束、被销毁时触发该方法。

 

**ServletRequestAttributeListener**则用于**监听ServletRequest（request）范围内属性的变化**。

实现该接口的监听器需要实现attributeAdded、attributeRemoved、attributeReplaced三个方法。由此可见，ServletRequestAttributeListener与ServletContextAttributeListener的作用相似，都用于监听属性的改变，只是ServletRequestAttributeListener监听request范围内属性的改变，而ServletContextAttributeListener监听的是application范围内属性的改变。