Article From:https://www.cnblogs.com/huangdabing/p/9219420.html

Listener, listener of attributes change in domain object

  The event listener of the change of the property in the domain object is used to monitor the listener of the attribute change information event in the three objects of ServletContext, HttpSession, HttpServletRequest.
  These three listener interfaces are respectivelyServletContextAttributeListener,
HttpSessionAttributeListener
And ServletRequestAttributeListener
,In these three interfaces, three methods are defined to handle the objects in the monitored object.Increases, deletions and substitutions of attributes,The same event has the same method name in the three interfaces, but only accepts different parameter types.

1.1、attributeAdded Method

  When an attribute is added to the monitored object, the web container responds to the attributeAdded method of the event listener, which receives an event type parameter that can be used by the listener to obtain the domain object that is increasing the property and the genus in the domain.Sexual object
  The complete syntax in each domain attribute listener is defined as:

 public void attributeAdded(ServletContextAttributeEvent scae)
 public void attributeAdded(HttpSessionBindingEvent  hsbe)
 public void attributeAdded(ServletRequestAttributeEvent srae)

1.2、attributeRemoved Method

  When an attribute in the monitored object is deleted, the web container invokes the attributeRemoved method of the event listener to respond.
  The complete syntax in each domain attribute listener is defined as:

1 public void attributeRemoved(ServletContextAttributeEvent scae)
2 public void attributeRemoved (HttpSessionBindingEvent  hsbe)
3 public void attributeRemoved (ServletRequestAttributeEvent srae)

1.3、attributeReplaced Method

  When an attribute in the domain object of the listener is replaced, the web container invokes the attributeReplaced method of the event listener to respond.
  The complete syntax in each domain attribute listener is defined as:

1 public void attributeReplaced(ServletContextAttributeEvent scae)
2 public void attributeReplaced (HttpSessionBindingEvent  hsbe)
3 public void attributeReplaced (ServletRequestAttributeEvent srae)

1.4、ServletContextAttributeListenerMonitorExample

  Write the ServletContextAttributeListener listener to monitor the change of the attribute value of the ServletContext domain object. The code is as follows:

package com.web.listener;

import java.text.MessageFormat;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;

/**
* @ClassName: MyServletContextAttributeListener
* @Description: ServletContextEvent listener for the change of property in a domain object*@author: hdb
* @date: 2014-9-11 10:53:04 p.m.**/ 
public class MyServletContextAttributeListener implements
        ServletContextAttributeListener {

    @Override
    public void attributeAdded(ServletContextAttributeEvent scab) {
        String str =MessageFormat.format(
                "ServletContextThe attribute is added to the domain object: {0}, and the attribute value is: {1} "
                ,scab.getName()
                ,scab.getValue());
        System.out.println(str);
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent scab) {
        String str =MessageFormat.format(
                "ServletContextDeleting properties in the domain object: {0}, the attribute value is: {1} "
                ,scab.getName()
                ,scab.getValue());
        System.out.println(str);
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent scab) {
        String str =MessageFormat.format(
                "ServletContextThe property of the domain object is replaced: the value of the {0} "
                ,scab.getName());
        System.out.println(str);
    }
}

  Register a listener in a web.xml file

  <listener>
       <description>MyServletContextAttributeListenerMonitor</description>
       <listener-class>com.web.listener.MyServletContextAttributeListener</listener-class>
   </listener>

  Write ServletContextAttributeListenerTest.jsp test page:

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title>ServletContextAttributeListenerThe listener test < /title>< /head>< body><%//Add properties to application domain objects
           application.setAttribute("name", "hdb");
          //Replace the value of the name property in the application domain object
           application.setAttribute("name", "coosee");
           //Remove the name property in the application domain object
           application.removeAttribute("name");
           %>
  </body>
</html>

  As you can see from the results of the run, the ServletContextListener listener successfully monitors the change in the value of the attribute values in the ServletContext domain object (application).

1.5、ServletRequestAttributeListenerAnd HttpSessionAttributeListener listenerExample

  Write listeners to monitor the changes of attribute values in HttpSession and HttpServletRequest domain objects. The code is as follows:

package com.web.listener;

import java.text.MessageFormat;

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class MyRequestAndSessionAttributeListener implements
        HttpSessionAttributeListener, ServletRequestAttributeListener {

    @Override
    public void attributeAdded(ServletRequestAttributeEvent srae) {
        String str =MessageFormat.format(
                "ServletRequestThe attribute is added to the domain object: {0}, and the attribute value is: {1} "
                ,srae.getName()
                ,srae.getValue());
        System.out.println(str);
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent srae) {
        String str =MessageFormat.format(
                "ServletRequestDeleting properties in the domain object: {0}, the attribute value is: {1} "
                ,srae.getName()
                ,srae.getValue());
        System.out.println(str);
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent srae) {
        String str =MessageFormat.format(
                "ServletRequestThe property of the domain object is replaced: the value of the {0} "
                ,srae.getName());
        System.out.println(str);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        String str =MessageFormat.format(
                "HttpSessionThe attribute is added to the domain object: {0}, and the attribute value is: {1} "
                ,se.getName()
                ,se.getValue());
        System.out.println(str);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
        String str =MessageFormat.format(
                "HttpSessionDeleting properties in the domain object: {0}, the attribute value is: {1} "
                ,se.getName()
                ,se.getValue());
        System.out.println(str);
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {
        String str =MessageFormat.format(
                "HttpSessionThe property of the domain object is replaced: the value of the {0} "
                ,se.getName());
        System.out.println(str);
    }
}

  Register a listener in a web.xml file

  <listener>
       <description>MyRequestAndSessionAttributeListenerMonitor</description>
       <listener-class>com.web.listener.MyRequestAndSessionAttributeListener</listener-class>
   </listener>

  Writing RequestAndSessionAttributeListenerTest.jsp test page

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title>RequestAndSessionAttributeListenerThe listener test < /title>< /head>< body><%//Add properties to session domain objects
           session.setAttribute("aa", "bb");
          //Replace the value of the AA property in the session domain object
           session.setAttribute("aa", "xx");
           //Remove the AA property in the session domain object
           session.removeAttribute("aa");
           
           //Add properties to request domain objects
           request.setAttribute("aa", "bb");
          //Replace the value of the AA property in the request domain object
           request.setAttribute("aa", "xx");
           //Remove the AA property in the request domain object
           request.removeAttribute("aa");
    %>
  </body>
</html>

  The results are as follows:

  

  As you can see from the running results, HttpSessionAttributeListener listeners and ServletRequestAttributeListener have successfully monitored the HttpSession domain objects and HttpS.The property value change of the ervletRequest domain object.

Two. An event listener aware of Session binding

  Objects stored in the Session domain can have a variety of states: binding (session.setAttribute (“bean”, Object)) into Session; from the Session domain (session.remove)Attribute (“bean”)) binding; persists with Session objects into a storage device; recovers from a storage device with Session objects.
  Servlet The specification is defined in the specificationTwo special listener interfaces “HttpSessionBindingListenerandHttpSessionActivationListener“To help JavaBeanThe object understands its own state in the Session domain: the classes that implement these two interfaces do not need to register in the web.xml file.

  For some POJO classes, they can be implementedHttpSessionBindingListenerAn interface that monitors the events of the POJO class object. For example:

public class User implements HttpSessionBindingListener,Serializable{

    private String username;
    private String password;
    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void valueBound(HttpSessionBindingEvent hsbe) {
        System.out.println("valueBound name: "+hsbe.getName());
    }

    public void valueUnbound(HttpSessionBindingEvent hsbe) {
        System.out.println("valueUnbound name: "+hsbe.getName());
    }
    
}

SessionPassivation and activation of data:

  Because session stores a lot of important information related to accessing web sites, too much session data will reduce server performance and occupy too much memory. Therefore, similar to the persistence of database objects, the web container also persists the infrequently used session data to the original.In a local document or data. These are all done by web container without user setting.

  The process of unused session data serialization to local files is passivation.

  When you visit the content of the session again, you will read the local file and put it in memory again.Activation.

  Similarly, as long as the HttpSeesionActivationListener interface is implemented, passivation and activation events are monitored.

public class User implements HttpSessionBindingListener,
HttpSessionActivationListener,Serializable{

    private String username;
    private String password;
    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void valueBound(HttpSessionBindingEvent hsbe) {
        System.out.println("valueBound name: "+hsbe.getName());
    }

    public void valueUnbound(HttpSessionBindingEvent hsbe) {
        System.out.println("valueUnbound name: "+hsbe.getName());
    }

    public void sessionDidActivate(HttpSessionEvent hsbe) {
        System.out.println("sessionDidActivate name: "+hsbe.getSource());
    }

    public void sessionWillPassivate(HttpSessionEvent hsbe) {
        System.out.println("sessionWillPassivate name: "+hsbe.getSource());
    }
    
}

2.1、HttpSessionBindingListenerInterface

  The JavaBean object that implements the HttpSessionBindingListener interface can perceive the event that it has been bound to Session and Session.
  When the object is bound to the HttpSession object, the web server invokes the void valueBound (HttpSessionBindingEvent event) method of the object.
  When the object is unbound from the HttpSession object, the web server invokes the void valueUnbound (HttpSessionBindingEvent event) method of the object.

Example:

package com.domain;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

/**
* @ClassName: JavaBeanDemo1
* @Description: 
*   The JavaBean object that implements the HttpSessionBindingListener interface can perceive that it is bound to Session and the event deleted from Session.When the object is bound to the HttpSessioIn the N object, the web server invokes the void valueBound (HttpSessionBindingEvent event) method of the object.When the object is unbound from the HttpSession objectThe web server invokes the void valueUnbound (HttpSessionBindingEvent event) method of the object.*@author: hdb
* @date: 2017-12-11 20:14:54
*
*/ 
public class JavaBeanDemo1 implements HttpSessionBindingListener {

    private String name;
    
    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println(name+"It was added to the session. ");
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println(name+"It was kicked out by session.);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public JavaBeanDemo1(String name) {
        this.name = name;
    }
}

  The above JavaBeanDemo1 JavaBean implements the HttpSessionBindingListener interface, and then the JavaBean object can perceive that it is bound to Session and from SessionDelete the two operations, the test code is as follows:

<%@ page language="java" pageEncoding="UTF-8"%>
<%@page import=" com.domain.JavaBeanDemo1"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title></title>
  </head>
  
  <body>
    <% 
        //Binding JavaBean objects to Session
        session.setAttribute("bean",new JavaBeanDemo1("hdb"));
        //Delete JavaBean objects from Session
        session.removeAttribute("bean");
    %>
  </body>
</html>

  The results are as follows:

  

2.2、HttpSessionActivationListenerInterface

  The JavaBean object that implements HttpSessionActivationListener interface can perceive its own activation (anti serialization) and passivation (serialization) events.
  When bound to the HttpSession object, the JavaBean object will follow the HttpSession object.Passivation(Serialization)Before, the web server invokes the void sessionWillPassivate (HttpSessionEvent event) method of the JavaBean object. In this way, JavaBean objects can know that they are going to have Ht.The tpSession object is serialized (passivated) to the hard disk.
  When bound to the HttpSession object, the JavaBean object will follow the HttpSession object.Be activated(Anti serialization)After that, the web server invokes the void sessionDidActive (HttpSessionEvent event) method of the JavaBean object. In this way, JavaBean objects can know that they are going to have HttpSe.Ssion objects are returned to memory by being serialized (activated).

Example:

package com.domain;

import java.io.Serializable;

import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;

/**
* @ClassName: JavaBeanDemo2
* @Description: 
    The JavaBean object that implements HttpSessionActivationListener interface can perceive its own activation and passivation events.Activation: the JavaBean object is serialized (activated) with Session.In memory.Passivation: the JavaBean object exists in Session, and when the server serializer session to the hard disk, if the JavaBean object in Session implements the Serializable interfaceThen suitThe server will serialize the JavaBean objects in session to the hard disk, and the operation that the JavaBean object and the Session are serialized into the hard disk is called passivation.If the JavaBean object in Session is not realWith the Serializable interface, the server first removes the JavaBean object that does not implement the Serializable interface in Session.Then the Session serialization (passivating) into the hard diskWhen bound toThe JavaBean object in the HttpSession object will be passivated with the HttpSession object.The web server invokes the void sessionWillPassivat of the JavaBean object object.E (HttpSessionEvent event) methodIn this way, the JavaBean object can know that it will be serialized (passivated) to the hard disk with the HttpSession object.When bound to HttpSessiThe JavaBean object in the on object will be activated after the HttpSession object is activated.The web server invokes the void sessionDidActive (HttpSessionEv) of the JavaBean object.Ent event) methodIn this way, JavaBean objects can know that they will be de serialized (activated) back to memory with HttpSession objects.*@author: hdb
* @date: 2017-12-11 20:22:35
*
*/ 
public class JavaBeanDemo2 implements HttpSessionActivationListener,
        Serializable {

     
    private static final long serialVersionUID = 7589841135210272124L;
    private String name;
    
    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        
        System.out.println(name+"Together with session, it is serialized (passivated) to the hard disk, and the ID of session is "+".se.getSession().getId());
    }

    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        System.out.println(name+"Back to memory with session from the hard disk serialization (activation), the session ID is: + +se.getSession().getId());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public JavaBeanDemo2(String name) {
        this.name = name;
    }
}

 

  In order to observe the process that the JavaBean object bound to the HttpSession object is passivated with the HttpSession object to the hard disk and reactivated from the hard disk back to memory, we need the help of the Tomcat server to help us complete the HttpSThe passivation and activation processes of ession objects are as follows:

  Create a context.xml file under the WebRoot\META-INF folder, as shown below:

  

  context.xmlThe contents of the document are as follows:

 <Context>
     <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
     <Store className="org.apache.catalina.session.FileStore" directory="gacl"/>
     </Manager>
 </Context>

  After 1 minutes in the context.xml file, the HttpSession object is passivated into a GaCl folder on the local hard disk.

  jspThe test code is as follows:

<%@ page language="java" pageEncoding="UTF-8"%>
<%@page import="com.domain.JavaBeanDemo2"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title></title>
  </head>
  
  <body>
      Once you access the JSP page, HttpSession is created, and the Id of the created Session is: ${pageContext.session.id}<hr/>
   <% 
        session.setAttribute("bean",new JavaBeanDemo2("hdb"));
    %>
  </body>
</html>

 

  After accessing this JSP page, the server will create a HttpSession object immediately, and thenRealizedHttpSessionActivationListenerThe JavaBean object of the interfaceBound to the session object, the JSP page will not be accessed again after 1 minutes, then the server will automatically passivate the HttpSession object (serialized) to the hard disk.

  

  We can find the session that is serialized to local storage under the work\Catalina\localhost\JavaWeb_Listener_20140908\gacl folder of the Tomcat server, as shown in the following figure:

  

  When the Jsp page is accessed again, the server automatically reactivates (serialized) the HttpSession object on the hard disk and reactivates (anti serialization) back into memory. The results are as follows:

  

  JavaWebThe content of the monitor technology in the development technology is so much. In the ordinary work, the monitor technology used in the development of JavaWeb project is much more, so it must be mastered.

Link of this Article: Listener learning (two)

Leave a Reply

Your email address will not be published. Required fields are marked *