JavaWeb之监听器

监听器

Servlet中存在一个EventListener接口,该接口有很多的子接口,如ServletContextListener、HttpSessionListener、ServletRequestListener等
用于监听ServletContext、HttpSession、ServletRequest等对象的创建和销毁,以及属性修改

监听ServletContext、HttpSession、ServletRequest等对象的创建和销毁

  • ServletContextListener 服务器启动时创建,调用contextInitialized方法;服务器正常关闭时销毁调用contextDestroyed方法
  • HttpSessionListener 第一次访request.getHttpSession创建,调用sessionCreated方法;调用invalidate或者过期销毁,调用sessionDestroyed方法
  • ServletRequestListener 每一次访问创建,调用requestInitialized方法; 响应结束销毁,调用requestDestroyed方法

以ServletContextListener为例

// 当Servlet容器启动或终止Web应用时,会触发ServletContextEvent事件,该事件由ServletContextListener处理
public interface ServletContextListener extends EventListener {
  	// 启动Web应用时调用该方法,该方法结束后才会对Filter进行初始化
    void contextInitialized(ServletContextEvent var1);
		// web应用终止时调用该方法,该方法在Servlet和Filter销毁之后调用
    void contextDestroyed(ServletContextEvent var1);
}

实现相应的接口,监听不同的域对象

<!-- web.xml -->
<listener>
	<listener-class>

场景:
ServletContextListener最常用,在当前WEB应用加载的时候对当前WEB应用的相关资源进行初始化操作:创建数据库连接池,创建Spring的IOC容器,读取当前WEB应用的初始化参数

监听域对象 ServletContext、HttpSession、ServletRequest 属性变更的监听器

  • ServletContextAttributeListener attributeAdded attributeRemoved attributeReplaced
  • HttpSessionAttributeListener attributeAdded attributeRemoved attributeReplaced
  • ServletRequestAttributeListener attributeAdded attributeRemoved attributeReplaced

感知session绑定的监听器

​ 保存到Session域中的对象可以有多种状态:绑定到Session中,从Session中解除绑定;随Session对象持久到到一个存储设备中;随Session对象从一个存储设备中恢复
​ HttpSessionBindingListener和HttpSessionActivationListener接口,实现这两个接口不需要在web.xml文件中注册

放到session中的对象实现HttpSessionBindingListener
会触发两个方法 绑定valueBound 解除valueUnBanding

实现了HttpSessionActivationListener接口的对象可以感知自己被钝化和被活化的事件
sessionWillPassivate 从内存写到磁盘 sessionDisActivate 从磁盘中读取出来

session会被存储在tomcat当前项目下 .cer文件

https://zhhll.icu/2021/javaweb/基础/6.监听器/

本文由mdnice多平台发布

  • 24
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拾光师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值