三、Listener介绍

来源:互联网 发布:淘宝店铺音乐要钱吗 编辑:程序博客网 时间:2024/06/06 04:55

使用Listener步骤:
- 定义Listenner实现类。
- 通过注解或在web.xml文件配置Listener。

3.1实现Listener类

常用Web事件监听器接口:
- ServletContextListener:用于监听Web应用的启动和关闭。
- ServletContextAttributeListener:用于监听ServletContext范围(application)内属性的改变。
- ServletRequestListener:用于监听用户请求。
- ServletRequestAttributeListener:用于监听ServletRequest范围(request)内属性的改变。
- HttpSessionListener:用于监听用户session的开始和结束。
- HttpSessionAttributeListener:用于监听HttpSession范围(session)内属性的改变。

ServletContextListener接口的方法:
- contextInitialized(ServletContextEvent sce):启动Web应用时,系统调用Listener的该方法。
- contextDestroyed(ServletContextEvent sce):关闭Web应用时,系统调用Listener的该方法。

@WebListenerpublic class GetConnListener implements ServletContextListener{    //应用启动时,该方法被电泳    public void contextInitialized(ServletContextEvent sce)    {    }    //系统关闭时,调用该方法    public void contextDestroyed(ServletContextEvent sce)    {    }}

3.2配置Listener

配置Listener的三种方式:
- 使用@WebListener修饰Listener实现类即可。
- 在web.xml文档中使用

<listener>     <!--指定Listener的实现类-->     <listener-class>package.className</listener-class></listener>

3.3使用ServletContextAttributeListener

ServletContextAttributeListener用于监听ServletContext(application)范围内属性的变化,实现该接口的方法需要实现如下三个方法:
- attributeAdded(ServletContextAttributeEvent event):当程序把一个属性存入application范围时触发该方法。
- attributeRemoved(ServletContextAttributeEvent event):当程序把一个属性从application范围删除时触发该方法。
- attributeReplaced(ServletContextAttributeEvent event):当程序替换application范围内的属性时将触发该方法。

3.4使用ServletRequestListener和ServletRequestAttributeListener

ServletRequestListener用于监听用户请求的到达,实现该接口的监听器需要实现如下两个方法:
- requestInitialized(ServletRequestEvent sre):用户请求到达、被初始化时触发该方法。
- requestDestroyed(ServletRequestEvent sre):用户请求结束、被销毁时触发该方法。

ServletRequestAttributeListener用于监听ServletRequest(request)范围内属性的变化。实现该接口的监听器需要实现attributeAdded()、attributeRemove()、attributeReplace()三个方法。

3.5使用HttpSessionListener和HttpSessionAtttributeListener

HttpSessionListener用于用户session的创建和销毁,实现该接口的监听器需要实现如下方法:
- sessionCreated(HttpSessionEvent se):用户与服务器的会话开始、创建时触发该方法。
- sessionDestroyed(HttpSessionEvent se):用户与服务器的会话断开、销毁时触发该方法。

HttpSessionAttributeListener则用于监听HttpSession(session)范围内属性的变化,实现该接口的监听器需要实现attributeAdded()、attributeRemoved()、attributeReplace()三个方法。

通过检查HttpServletRequest的做法可以更精确地监控在线用户的状态:
- 定义一个ServletRequestListener,这个监听器负责监听每个用户请求,当用户请求到达时,系统将用户的session ID、用户名、用户IP、正在访问的资源、访问时间记录下来。
- 启动一条后台线程,这条后台线程每隔一段时间检查上面的每条在线记录,如果某条在线记录的访问时间与当前时间相差超过了指定值,将这条在线记录删除即可。这条后台线程应随着Web应用的启动而启动,可考虑使用ServletContextListener来完成。

0 0
原创粉丝点击