Listener监听类

来源:互联网 发布:c语言逻辑表达式|x|>4 编辑:程序博客网 时间:2024/05/20 07:59

Web应用的Listener监听类主要用于包括:ServletContetAttributeListener/ServletRequestListener/ServletRequestAttributeListener/HttpSessionListener/HttpSessionAttributeListener五个,在使用之前我们需要在web配置文件中配置Listener,配置Listener监听类的方式很简单,只需要向web应用注册Listener监听类就可以了。注册Listener监听类的方式有两种:
1>使用注解@WebListener修饰Listener类即可
2>在web.xml配置文件使用该标签:




下面介绍五个常用的Listener的用法:
1>ServletContextLisener:用于监听ServletContext也就是application内置对象(代表JSP/Servlet所属的web应用本身)范围内的属性。实现该接口的监听类需要实现下面三个方法:
1>void attributeAdded(ServletContextAttributeEvent event):用于监听application范围的属性的新增事件
2>void attributeRemoved(ServletContextAtttributeEvent event):用于监听application范围内的属性的删除事件
3>void attributeReplaced(ServeltContextAttributeEvent event):用于监听application范围内的属性的修改事件

2>ServletRequestListener:用于监听用户请求的到达,也就是监听request内置对象的生命周期。实现该监听类需要实现下面两个方法:
1>void requestInitialized(ServletRequestEvent event):用户请求到达并被初始化时触发该事件
2>void requestDestroyed(ServletRequestEvent event):用户请求结束辈销毁是触发该事件

3>ServletRequestAttributeListener:该监听类是监听request范围内的属性的变化,实现该监听类需要实现类似于ServletContextListener的三个方法:
1>void attributeAdded(SevletRequestAttributeEvent event):用于监听request范围的属性的新增
2>void attributeRemove(ServletRequestAttributeEvent event):用于监听request范围的属性的删除
3>void attributeReplaced(ServletRequestAttributeEvent event):用于监听request范围的属性的修改

4>HttpSessionListener:该Listenern用于监听session会话的开始和结束,实现该监听类需要实现下面两个方法:
1>void sessionInitialized(HttpSessionEvent event):用户和服务器的会话开始时触发该事件
2>void sessionDestroyed(HttpSessionEvent event):用户和服务器的会话断开时触发该事件

5>HttpSessionAttributeListener:该Listener用于监听session范围内的属性,实现该Listener需要实现下面三个方法:
1>void attributeAdd(HttpSessionAttributeEvent event) : 用于监听session范围的属性的新增事件
2>void attributeRemoved(HttpSessionAttributeEvent event):用于监听session范围的属性的移除事件
3>void attributeReplaced(HttpSessionAttributeEvent event):用于监听session范围的属性的修改事件

0 0