Listener(监听器)

tech2022-07-08  202

使用步骤

自定义类实现Listener接口着重实现方法注册 – @WebListener – web.xml <listener> <listener-class>e_listener.MyServletContextListener</listener-class> </listener>

三大域对象监听器

– application域 – session域 – request域 分别对应:创建和销毁 、域内容的改变

(重点掌握) ServletContextListener:监测服务器的开启和关闭 功能: 1. 周期性调度 2. 应用的初始化设置 3. 加载一些配置文件

@WebListener public class MyServletContextListener implements ServletContextListener { // 在ServletContext对象创建时调用 @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("application 创建了"); } // 检测到ServletContext对象的销毁,并且调用该方法 @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("application 销毁了"); } }

ServletContextAttributeListener:监测ServletContext域内容的改变

// getAttribute() -- 没有改变属性内容 // 首次 setAttribute("name", 123) @Override public void attributeAdded(ServletContextAttributeEvent scae) { System.out.println("add 新的内容"); } // removeAttribute() @Override public void attributeRemoved(ServletContextAttributeEvent scae) { System.out.println("remove 一个属性"); } // 再次setAttribute("name", 345) @Override public void attributeReplaced(ServletContextAttributeEvent scae) { System.out.println("replace 一个属性"); }

对象感知监听器

绑定与解绑的监听器:HttpSessionBindingListener 钝化与活化的监听器:HttpSessionActivationListener

将对象存储在session中和将对象从session中移除session对象的钝化、活化 session钝化:将session数据持久化到磁盘上 session活化:将磁盘上的session文件恢复到内存中

注意: 都是通过对象流写入磁盘上 – String name -> 可以保存在磁盘上(已经序列化) – User user -> 不能保存在磁盘上,必须序列化,需要实现Serializable接口

设置session钝化时间

<Context docBase="/Users/bonnie/IdeaWorks/javaweb/out/artifacts/web_war_exploded"> <!-- maxIdleSwap:session中的对象多长时间不使用就钝化 --> <!-- directory:钝化后的对象的文件写到磁盘的哪个目录下,配置钝化的对象文件在 work/catalina/localhost/钝化文件 --> <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1"> <Store className="org.apache.catalina.session.FileStore" directory="bonnie" /> </Manager> </Context>
最新回复(0)