web开发之监听器

监听器

监听器概述

专门用于对域对象身上发生的事件或状态改变进行监听和相应处理的对象

  • 监听器是GOF设计模式中,观察者模式的典型案例
  • 观察者模式:当被观察的对象发生某些改变时,观察者自动采取对应的行动的一种设计模式
  • 监听器使用的感受类似于JS中的事件,被观察的对象发生某些情况时,自动触发代码的执行
  • 监听器并不监听web项目中的所有组件,只是对三大域对象做相关的事件监听

监听器的分类

  • web中定义八个监听器接口作为监听器的规范,这八个接口按照不同的标准可以形成不同的分类
  • 按监听的对象划分
    • application域监听器 ServletContextListener ServletContextAttributeListener
    • session域监听器 HttpSessionListener HttpSessionAttributeListener HttpSessionBindingListener HttpSessionActivationListener
    • request域监听器ServletRequestListener ServletRequestAttributeListener
  • 按监听的事件分
    • 域对象的创建和销毁监听器ServletContextListener HttpSessionListener ServletRequestListener
    • 域对象数据增删改查事件监听器ServletContextAttributeListener HttpSessionAttributeListener ServletRequestAttributeListener
    • 其他监听器HttpSessionBindingListener HttpSessionActivationListener

例子

@Listener
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        // 在应用程序启动时执行的初始化操作
        System.out.println("应用程序已启动!");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // 在应用程序关闭时执行的清理操作
        System.out.println("应用程序已关闭!");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值