5.监听器(Listener)

本文详细介绍了Java Web中的监听器,包括ServletContext监听器、HttpSession监听器和ServletRequest监听器。监听器用于监听对象创建、属性变化等事件。ServletContextListener在应用启动和关闭时执行初始化和清理工作;HttpSessionListener关注Session的创建和销毁;ServletRequestListener则监听每个请求的生命周期。同时,还讲解了与之相关的属性监听器和事件处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.监听器简介

       监听器主要用来监听对象的创建,属性的变化,是一个实现特定接口的普通Java类。

      Listener接口与事件对应表:

    

ServletContext

有关

ServletContextListener

ServletContextEvent

ServletContextAttributeListener

ServletContextAttributeEvent

HttpSession

有关

HttpSessionListener

HttpSessionEvent

HttpSessionActivationListener

HttpSessionAttributeListener

HttpSessionBindingEvent

HttpSessionBindingListener

ServletRequest

有关

ServletRequestListener

ServletRequestEvent

ServletRequestAttributeListener

ServletRequestAttributeEvent

 

 

     编写监听器的步骤:

       编写实现类->在web.xml中进行部署->编写测试页面

2.与ServletContext相关监听器

   

单个Web站点的资源都共享一个javax.servlet.ServletContext类的实体。通过该对象可以存取应用程序的全局对象以及初始化阶段的变量
全局对象即为Application范围对象,其生命周期从容器启动至容器关闭。初始阶段的变量是指在web.xml中,由<context-param>元素设定的变量,该变量的范围是Application范围

ServletContextListener接口:

实现了该接口的程序,当JavaWeb应用程序启动时,会自动开始监听工作

首先调用contextInitialized()方法接收对应的ServletContextEvent事件

当应用从容器中移除时,会自动调用contextDestroyed()方法

以上两个方法都会接收到ServletContextEvent事件对象,该对象可以调用getServletContext()方法取得ServletContext对象(全局对象)

ServletContextAttributeListener接口:

实现该接口的程序,能够监听ServletContext属性的变化,例如:当往ServletContext中添加数据时,该程序会被调用。

 

 

方法

说明

attributeAdded(ServletContextAttributeEvent  e)

若有对象加入Application范围时,通知

 

正在收听的对象

attributeReplaced(ServletContextAttributeEvent  e)

若在Application的范围,有对象取代另

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值