1. 监听器简介:
当web应用在web容器中运行时,web应用内部会不断地发生各种事件:如web应用被启动,web应用被停止,用户session开始,用户session结束,用户请求到达等。通常来说,这些web事件对开发者来说是透明的。
实际上,Servlet API提供了大量监听器来监听web应用的内部事件,从而允许当web内部事件发生时,回调事件监听器的方法。
使用Listener只需要两个步骤:
1. 定义Listener实现类
2. 在web.xml文件中配置Listener
2. Listener的实现:
与AWT事件编程完全类似,监听不同web事件的监听器也不相同。常用的web事件监听器接口有如下几个:
1. ServletContextListener:用于监听web应用的启动和关闭。
1. contextInitialized(ServletContextEvent sce):启动web应用时,系统回调该方法。
2. contextDestroyed(ServletContextEvent sce):关闭web应用时,系统回调该方法。
2. ServletContextAttributeListener:用于监听ServletContext范围内属性的改变。
1. attributeAdded(ServletContextAttributeEvent event):当程序把一个属性存入application时触发该方法。
2. attributeRemoved(ServletContextAttributeEvent event):当程序把一个属性从application范围内删除时触发该方法。
3. attributeReplaced(ServletContextAttributeEvent event):当程序替换aplication范围内的属性时触发该方法。
3. ServletRequestListener:用于监听用户请求的到达。
1. requestInitialized(ServletRequestEvent sre):用户请求到达,被初始化时触发该方法。
2. requestDestroyed(ServletRequestEvent sre):用户请求结束,被销毁时触发该方法。
4. ServletRequestAttributeListener:用于监听request范围内属性的变化。
1. attributeAdded(ServletRequestAttributeEvent event):
2. attributeRemoved(ServletRequestAttributeEvent event):
3. attributeReplaced(ServletRequestAttributeEvent event):
5. HttpSessionListener:用于监听用户session的创建和销毁。
1. sessionCreated(HttpSessionEvent event)
2. sessionDestroyed(HttpSessionEvent event)
6. HttpSessionAttributeListener:用于监听session范围内属性的变化。
1. attributeAdded(HttpSessionBindingEvent event):
2. attributeRemoved(HttpSessionBindingEvent event) :
3. attributeReplaced(HttpSessionBindingEvent event) :