如何使用监听器Servlet
Listener 是 Servlet 规范里的监听器。它可以监听 ServletContext、HttpSession、ServletRequest 等域对象的创建与销毁,以及属性增删改,在事件前后做必要处理。
典型用法是统计在线人数:新建一个 HttpSession 就加一,销毁就减一。监听器写在 web.xml 里,不必改现有业务代码就能挂上。
接口分成两类:监听域对象本身的生灭,以及监听域对象上的属性变化。容器会根据你实现的接口自动回调对应方法。
一、监听器概述
-
Listener 是 Servlet 的监听器。 -
可监听 Context / Session / Request 的创建与销毁,以及属性修改。 -
事件发生时自动激发操作,例如在线用户计数。
二、常用的监听接口
1. 监听域对象的创建与销毁
ServletContextListener:创建时回调 contextInitialized,销毁时回调 contextDestroyed。
HttpSessionListener:创建 Session 时回调 sessionCreated,销毁时回调 sessionDestroyed。
ServletRequestListener:监听请求对象 ServletRequest 的创建与销毁。

2. 监听域对象属性的增加和删除
ServletContextAttributeListener:监听对 ServletContext 属性的增加 / 删除 / 修改。
HttpSessionAttributeListener:Session 增加属性时 attributeAdded,删除时 attributeRemoved,覆盖时 attributeReplaced,事件类型是 HttpSessionBindingEvent。
ServletRequestAttributeListener:监听 ServletRequest 中的属性操作。
| 接口 | 监听对象 | 关键回调 |
|---|---|---|
| ServletContextListener | 应用上下文 | contextInitialized / contextDestroyed |
| HttpSessionListener | 会话 | sessionCreated / sessionDestroyed |
| ServletRequestListener | 一次请求 | requestInitialized / requestDestroyed |
| ServletContextAttributeListener | Context 属性 | added / removed / replaced |
| HttpSessionAttributeListener | Session 属性 | added / removed / replaced |
| ServletRequestAttributeListener | Request 属性 | added / removed / replaced |
三、由监听器管理共享数据库连接
生命周期事件的一个实际应用:用 Context 监听器管理共享数据库连接。在 web.xml 中声明:
容器会创建监听器实例,根据实现的接口类型分发事件。监听器配在部署描述符里,添加新监听器不必改业务代码。
这样每个新生成的 ServletContext 都有可用连接,Context 关闭时连接随之关闭。
四、计算在线用户数量
用一个计数器和 Session 监听器配合:
需要显示在线人数的 JSP:
给用户一个注销按钮,在 exit.jsp 里让会话失效:
在 web.xml 中加入:
不用对现有业务代码做修改,只要把监听器挂上即可。
一句话总结:监听器挂在 web.xml 里:容器在 Context / Session / Request 生灭时回调,适合放共享资源和计数。
转载请注明来源:如何使用监听器Servlet









