监听器
Servlet中存在一个EventListener接口,该接口有很多的子接口,如ServletContextListener、HttpSessionListener、ServletRequestListener等
用于监听ServletContext、HttpSession、ServletRequest等对象的创立和销毁,以及属性批改
<!-- more -->
监听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多平台公布