三、Listener介绍

使用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的该方法。

@WebListener
public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值