监听器 Listener,Web应用在Web容器中运行时,Web内部会不断发生各种事件: 像Web应用被启动、Web应用被停止,用户 Session开始、用户Session 结束、用户请求到达等等,这些应用对开发者来说是透明的。
实际上,在Servlet API 中, 提供了大量监听内部事件;使用Listener 的两个步骤:
1、定义Listener实现类
2、通过 Annotation 或在 web.xml 文件中配置 Listener
跟 AWT 编程相似,监听不同的Web事件有不同的 监听器:
ServletContextListener: web应用的启动、关闭
ServletContextAttributeListener: ServletContext范围(application)内属性的改变
ServletRequestListener: 监听用户请求
ServletRequestAttributeListener: ServletRequest范围(application)内属性的改变
HttpSessionListener:监听Session的开始、结束
HttpSessionAttributeListener:HttpSession范围(Session)内属性的改变
ServletContextListener为例子:
两个方法:
contextInitialized( ServletContextEvent sce ):启动Web应用时,系统调用Listener 的该方法
contextDestroyed( ServletContextEvent sce ):关闭Web应用时,系统调用Listener的该方法
这两个方法可以重写,用于Web应用提供全局服务
……
public void contextInitialized(ServletContextEvent sce){
ServletContext application = sce.getServletContext();
……
}
……
配置 Listener:
1、使用@WebListener 修饰 Listener 实现类
2、在 web.xml 文档中使用< listener…… /> 元素进行配置
需要指定子元素: listener-class :指定实现类
例如:
<span style="white-space:pre"> </span><listener>
<listener-class> atomic.xxxxListener </listener-class>
</listener>
ServletContextAttributeListener:
监听 ServletContext 范围内属性变化,三个方法:
attributeAdded(ServletContextAttributeEvent event):当程序把一个属性存入application 范围时,触发该方法
attributeRemoved(ServletContextAttributeEvent event):当程序把一个属性从application范围删除时,触发该方法
attributeReplaced(ServletContextAttributeEvent event):当程序替换application范围内的属性时将触发该方法