zoukankan      html  css  js  c++  java
  • 【Java EE 学习 21 上】【其它类型的监听器】【使用HttpSessionActivationListener监听session的活化和钝化】

    一、ServletContextListener 

    Method Summary

     void

    contextDestroyed(ServletContextEvent sce)
              Receives notification that the ServletContext is about to be shut down.

     void

    contextInitialized(ServletContextEvent sce)
              Receives notification that the web application initialization process is starting.

    代码举例:

    package com.kdyzm.listener;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    public class MyServletContextListener implements ServletContextListener{
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            ServletContext sc=sce.getServletContext();
            System.out.println(sc+"被销毁!");
        }
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            System.out.println(sce.getServletContext()+"初始化!");
        }
        
    }
    ServletContextListener举例

    二、ServletContextAttributeListener

    Method Summary

     void

    attributeAdded(ServletContextAttributeEvent event)
              Receives notification that an attribute has been added to the ServletContext.

     void

    attributeRemoved(ServletContextAttributeEvent event)
              Receives notification that an attribute has been removed from the ServletContext.

     void

    attributeReplaced(ServletContextAttributeEvent event)

     使用方法和HttpSessionAttriuteListener的用法相似,略。

    三、HttpSessionBindingListener

    Method Summary

     void

    valueBound(HttpSessionBindingEvent event)
              Notifies the object that it is being bound to a session and identifies the session.

     void

    valueUnbound(HttpSessionBindingEvent event)
              Notifies the object that it is being unbound from a session and identifies the session.

      1.功能:监听一个Bean是否被放到了Session中。

      2.特点:该接口需要被Bean实现才能正常发挥作用,实现该接口的Bean不需要配置到web.xml文件中。

      3.举例说明:

    package com.kdyzm.domain;
    
    import javax.servlet.http.HttpSessionBindingEvent;
    import javax.servlet.http.HttpSessionBindingListener;
    
    public class Person implements HttpSessionBindingListener{
        private String name;
        public Person() {
        }
    
        public Person(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Person [name=" + name + "]";
        }
    
        @Override
        public void valueBound(HttpSessionBindingEvent event) {
            System.out.println(this+"被加入到session中!");
        }
    
        @Override
        public void valueUnbound(HttpSessionBindingEvent event) {
            System.out.println(this+"被移出session!");
        }
        
    }
    实现了HttpSessionBindingListener接口的Bean
    <%@page import="com.kdyzm.domain.Person"%>
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8" 
        contentType="text/html; charset=utf-8" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <title>Insert title here!</title>
      </head>
      
      <body>
        <%
            Person p=new Person("小黄");
            session.setAttribute("p", p);
            out.println(session.getAttribute("p"));
            session.removeAttribute("p");
            out.println(session.getAttribute("p"));
        %>
      </body>
    </html>
    index.jsp测试JSP文件

     浏览器显示:

    控制台显示:

    Person [name=小黄]被加入到session中!
    Person [name=小黄]被移出session!

    四、HttpSessionActivationListener

    Method Summary

     void

    sessionDidActivate(HttpSessionEvent se)
              Notification that the session has just been activated.

     void

    sessionWillPassivate(HttpSessionEvent se)
              Notification that the session is about to be passivated.

      1.功能:监听到一个session被保存到一个文件或者从文件中加载session的过程。

      2.特点:也需要一个Bean实现该接口,而且也不需要配置到web.xml文件中。

      3.小练习:在服务器关闭的时候将所有session保存到文件(钝化),服务器开启之后,再将session恢复到服务器内存。

         源代码:https://github.com/kdyzm/day21_1

         第一步:建立Person类并实现HttpSessionActivationListener接口。

    package com.kdyzm.domain;
    
    
    import javax.servlet.http.HttpSessionActivationListener;
    import javax.servlet.http.HttpSessionEvent;
    
    public class Person implements HttpSessionActivationListener{
        private String name;
        public Person() {
        }
    
        public Person(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Person [name=" + name + "]";
        }
    
        @Override
        public void sessionDidActivate(HttpSessionEvent se) {
            System.out.println(se.getSource()+" 从文件恢复到内存!");
        }
    
        @Override
        public void sessionWillPassivate(HttpSessionEvent se) {
            System.out.println(se.getSource()+" 从内存保存到文件!");
        }
    }
    实现了HttpSessionActivationListener接口的Person类

         第二步:配置配置文件,在%tomcat_home%/conf/Catalina/localhost目录下新建xml文件abc.xml,在xml文件中进行如下配置:

    <?xml version="1.0" encoding="gbk"?>
    <Context docBase="E:\MyEclipseWorkSpace\day21_1\WebRoot">
        <Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="true">
            <Store className="org.apache.catalina.session.FileStore" directory="d:/a">
            </Store>
        </Manager>
    </Context>
    abc.xml配置文件

         第三步:创建jsp文件进行测试,这里直接使用index.xml文件

    <%@page import="com.kdyzm.domain.Person"%>
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8" 
        contentType="text/html; charset=utf-8" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <title>Insert title here!</title>
      </head>
      
      <body>
          <%
              if(session.getAttribute("p")==null)
              {
                  Integer a=new Random().nextInt(100);
                  session.setAttribute("p", new Person(a.toString()));
              }
          %>
          ${p}<br/>
          <%
              System.out.println(session.getId());
          %>
      </body>
    </html>
    index.xml文件

         第四步:打开浏览器,在浏览器上输入:http://localhost:8080/abc,回车,观察输出结果。

           (1)浏览器输出结果

            

           (2)控制台输出结果

           

           控制台输出结果是当前会话的sessionid。

          (3)打开D://a目录,查看有没有session文件,结果是没有

        第五步:通过shutdown的方式关闭服务器。再次观察现象

          (1)控制台输出:显示了将session保存到了文件

          

          (2)查看D://a目录看看有没有相应的session文件,结果是有,而且session文件的名字就是sessionid

          

          (3)刷新原来的页面,看看数值是否有变化,结果是变化了;再看看后台打印输出的结果,比较是否是同一个session,确实是同一个session

            疑问:后台没有打印输出“当前对象没有从文件中活化”的提示,既然从session文件中活化了,为什么数值会发生变化

            结果图片:

            

            

        第六步:解决疑问

        让Person类实现Serializable接口,一切问题就都解决了。

    package com.kdyzm.domain;
    
    
    import java.io.Serializable;
    
    import javax.servlet.http.HttpSessionActivationListener;
    import javax.servlet.http.HttpSessionEvent;
    
    public class Person implements HttpSessionActivationListener,Serializable{
        private String name;
        public Person() {
        }
    
        public Person(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Person [name=" + name + "]";
        }
    
        @Override
        public void sessionDidActivate(HttpSessionEvent se) {
            System.out.println(se.getSource()+" 从文件恢复到内存!");
        }
    
        @Override
        public void sessionWillPassivate(HttpSessionEvent se) {
            System.out.println(se.getSource()+" 从内存保存到文件!");
        }
    }
    实现了Seriable接口、HttpSessionActivationListener接口的Person类

        (1)重复之前的步骤,最后重启服务器,刷新网页,查看后台输出结果和网页现实的数值是否有变化。

          浏览器:第一次打开的时候是

          

          重启服务器之后再次刷新页面,结果相同。

          服务器控制台:

          

          显示了从文件恢复到内存的提示信息。

          

  • 相关阅读:
    c# out ref parames的用法
    c#测试执行时间的方法
    c#文件的操作
    c#md5加密的简单用法
    notepad++加到右键
    mysql自动安装脚本
    Arrays.sort实现原理
    选择排序
    自带排序 Array.sort()
    vi中使用鼠标右键插入时进入(insert)visual模式
  • 原文地址:https://www.cnblogs.com/kuangdaoyizhimei/p/4592900.html
Copyright © 2011-2022 走看看