JavaWeb 之监听器

1. JavaWeb 监听器概述

  • 在 JavaWeb 被监听的事件源为: ServletContext, HttpSession, ServletRequest, 即三大域对象.
  • 监听域对象"创建"与"销毁"的监听器;
  • 监听域对象"操作域属性"的监听器;
  • 监听 HttpSession 的监听器;
  • J2EE 文档 javax.servlet 包下;
ServletContext 事件源
  1. 生命周期监听: ServletContextListener, 它有两个方法, 一个在出生后调用,一个在死亡前调用;

    • void contextInitialized(ServletContextEvent sce);: 创建 ServletContext 时,调用;
    • void contextDestroyed(ServletContext sce);: 销毁 ServletContext 时, 调用;
  2. 属性监听: ServletContextAttributeListener,它有三个方法:

    • void attributeAdded(ServletContextAttributeEvent event);: 添加属性时调用;
    • void attributeReplaced(ServletContextAttributeEvent event);: 替换属性时调用;
    • void attributeRemoved(ServletContextAttributeEvent event);: 移除属性时调用
HttpSession 事件源
  • 生命周期监听: HttpSessionListener
  • 属性监听: HttpSessionAttributeListener
ServletRequest 事件源
  • 生命周期监听: ServletRequestListener
  • 属性监听: ServletRequestAttributeListener
事件对象
  1. ServletContextEvent:
    • 主要方法 ServletContext getServletContext(), 获取事件源;
  2. HttpSessionEvent
    • HttpSesssion getSession(), 获取事件源;
  3. ServletRequest
    • ServletContext getServletContext();
    • ServletRequest getServletRequest();
  4. ServletContextAttributeEvent
    • ServletContext getServletContext(): 获取事件源;
    • String getName(): 获取属性名;
    • Object getValue(): 获取替换之前的属性值;

2. 感知监听

2.1 特点
  • 它用来添加到 JavaBean 上,而不是添加到三大域上!
  • 这两个监听器都不需要在 web.xml 中注册;
  • 与 HttpSession 相关.
2.2 监听器
  1. HttpSessionBindingListener, 它有两个方法
    • void valueBound(HttpSessionBindingEvent event);
    • void valueUnbound(HttpSessionBindingEvent event);

3. session 钝化和活化相关的监听器

  • Tomcat 会在 session 长时间不被使用时钝化 session 对象, 所谓钝化 session, 就是把 session 通过
    序列化的方式保存到硬盘文件中. 当用户再使用 session 时, Tomcat 还会把钝化的对象再活化 session,
    所谓活化就是把硬盘文件中的 session 在反序列化会内存.
3.1 监听器
  1. HttpSessionActivationListener, 它有两个方法

    • public void sessionWillPassivate(HttpSessionEvent event): 当对象感知被活化时调用本方法;
    • public void sessionDidActivate(HttpSessionEvent event): 当对象感知被钝化时调用本方法;
  2. 配置 Tomcat 钝化 session 的参数, 目录: tomcat/conf/catalina/localhost, 文件名称为项目名称

<Context>
    // 该参数固定, maxIdleSwap 表示 session 最大不活动时间 1 分钟
    <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">

    // 设置 session 序列化地址 Tomcat/work/catalina/localhost/listener/mysession 目录下
    <Store className="org.apache.catalina.session.FileStore" directory="mysession"/>
</Context>

参考资料:

原文地址:https://www.cnblogs.com/linkworld/p/7634286.html