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

1. Introduction of a listener

1.1、The concept of the listener

  A listener is an object that is used to monitor and handle the events or state changes that occur on other objects. When the monitored objects occur, the corresponding action is taken immediately. A listener is actually an ordinary Java program that implements a specific interface, which is dedicated to monitoring another.A method call or property change of a Java object. When the monitored object happens, the listener method is executed immediately.

1.2、Listener case — listener for event listener in window window

package com.listener.demo;

import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class Demo1 {

    /**
     * javaEvent monitoring mechanism* 1, event monitoring involves three components:Event source, event object, event listener
     * 2、When an action occurs on the event source, it invokes a method of event listener and transfers the event object when invoking the method.The developer can get the event source through event object in the listener, so as to operate the event source.*/
    public static void main(String[] args) {
        
        Frame f = new Frame();
        f.setSize(400, 400);
        f.setVisible(true);
        
        //Register event listener
        f.addWindowListener(new WindowListener(){

            public void windowActivated(WindowEvent e) {
                
            }

            public void windowClosed(WindowEvent e) {
                
            }

            /**
             * When the window form closes, WindowListener listener listens.* the listener will invoke the windowClosing method to handle the actions when the window forms are closed.     */
            public void windowClosing(WindowEvent e) {
                //The event source object is obtained by the event object e
                Frame f = (Frame) e.getSource();
                System.out.println(f+"The form is closing ");
                f.dispose();
            }

            public void windowDeactivated(WindowEvent e) {
                
            }

            public void windowDeiconified(WindowEvent e) {
                
            }

            public void windowIconified(WindowEvent e) {
                
            }

            public void windowOpened(WindowEvent e) {
                
            }
        });
    }
}

1.3、Design an object that can be monitored by other objects

  When we do development, we write a listener to monitor other objects, so if we want to design an object to be monitored by other objects and how to do it, we can design an object according to a strict event processing model, which can be monitored by other objects and events.The model involves three components:Event source, event object, event listener

  Next we will design a Person object according to the event handling model.The specific code is as follows:

package com.observer;

/**
* @ClassName: Person(Source of events)* @Description: designs a Person class as an event source. The behavior of objects in this class, such as eating and running, can be monitored by other objects.*@author: hdb
* @date: 2017-11-9 20:26:06
*
*/  
public class Person {
    /**
    * @Field: listener
    *  Define a PersonListener variable in the Person class to remember the incoming listener.*/ 
    private PersonListener listener;

    /**
    * @Method: eat
    * @Description: The behavior of designing Person: eat* @Anthor:hdb**/ 
    public void eat() {
        if (listener != null) {
            /**
             * Calling the listener's doeat method listens to the Person class object eat (eat) action, passing the event object Event to the doeat method.* event objects encapsulate event sources,new Event(this)The this in it represents the source of the event*/
            listener.doeat(new Event(this));
        }
    }

    /**
    * @Method: run
    * @Description: The behavior of designing Person: running* @Anthor:hdb**/ 
    public void run() {
        if (listener != null) {
            /**
             * Calling the listener's dorun method listens to the Person class object run (run) action, passing the event object Event to the doeat method.* the event object encapsulates the event source, new Event (this).This represents the source of the event*/
            listener.dorun(new Event(this));
        }
    }

    /**
    * @Method: registerListener
    * @Description: This method is used to register listeners for monitoring the behavior of Person class objects.* @Anthor:hdb**@param listener
    */ 
    public void registerListener(PersonListener listener) {
        this.listener = listener;
    }
}

/**
* @ClassName: PersonListener(Event listener)* @Description: design listener interface for Person class (event source).*@author: hdb
* @date: 2017-11-9 9:28:06 p.m.**/ 
interface PersonListener {

    /**
    * @Method: doeat
    * @Description: This method is used to monitor the behavior of Person object eat (eat).* when the implementation class implements the doeat method, you can listen to the Person class object eat (eat) action.*Anthor:hdb**@param e
    */ 
    void doeat(Event e);

    /**
    * @Method: dorun
    * @Description: This method is used to monitor the behavior of Person object run (run).* when the implementation class implements the dorun method, you can listen to the Person class object run (run) action.*Anthor:hdb**@param e
    */ 
    void dorun(Event e);

}

/**
* @ClassName: Event(Event object)* @Description: design event classes to encapsulate event sources.*@author: hdb
* @date: 2017-11-9 9:37:56 p.m.**/ 
class Event {

    /**
    * @Field: source
    *          The source of the event (Person is the source of the event)*/ 
    private Person source;

    public Event() {
        
    }

    public Event(Person source) {
        this.source = source;
    }

    public Person getSource() {
        return source;
    }

    public void setSource(Person source) {
        this.source = source;
    }
}

  After such a design, the object of the Peron class can be monitored by other objects. The test code is as follows:

package com.observer;

public class PersonTest {

    /**
     * @Method: main
     * @Description: Test the Person class* @Anthor:hdb**@param args
     */
    public static void main(String[] args) {
        //
        Person p = new Person();
        //A listener that registers to listen to the behavior of P objects
        p.registerListener(new PersonListener() {
            //Listen to the behavior of P eating
            public void doeat(Event e) {
                Person p = e.getSource();
                System.out.println(p + "In eating "food");
            }
            //Listen to the behavior of P running
            public void dorun(Event e) {
                Person p = e.getSource();
                System.out.println(p + "In running ");
            }
        });
        //pEating food
        p.eat();
        //pIn running
        p.run();
    }
}

Running results:

  com.observer.Person@4a5ab2Eating food
  com.observer.Person@4a5ab2In running

The listener in two, JavaWeb

 

2.1、Basic concepts

Concept:

  JavaWebThe listener is a special class defined in the Servlet specification, which is used to monitor the creation and destruction of domain objects such as ServletContext, HttpSession and ServletRequest in a web application, and to monitor thisAn event that changes the properties of some domain objects. When the state of the scope object changes, the server automatically invokes the method in the listener object.

Use:

  Statistics online numbers and online users, using HttpSessionLisener

  Initialization of information when the system is loaded: using ServletContextListener

  Statistical website access

  Realizing access monitoring

2.2、ServletThe classification of the listener

  Various types of listeners are defined in the Servlet specification, which are used to monitor event sources separately.ServletContextHttpSessionandServletRequestThese three domain objects
  ServletStandardize the operations on these three objects, and divide various types of listeners into three types:

  1. Monitoring domainThe creation and destruction of the object itselfThe event listener.
  2. Monitoring domainobjectProperties increase and deleteThe event listener.
  3. MonitorBinding to the state of an object in the HttpSession domainThe event listener.

2.3、Monitor the creation and destruction of ServletContext domain objects

  ServletContextListenerInterfaces are used to monitor the creation and destruction of ServletContext objects. Classes that implement ServletContextListener interfaces can monitor and create ServletContext objects.

  When the ServletContext object isEstablishTimecontextInitialized (ServletContextEvent sce)Method.

  When the ServletContext object isDestroyTimecontextDestroyed(ServletContextEvent sce)Method.

  ServletContextThe time to create and destroy domain objects:
    Create: server startup to create ServletContext for every Web application.
    Destruction: shut down the ServletContext representing each web application before the server closes.

Example: write a MyServletContextListener class.Implement ServletContextListener interface and monitor the creation and destruction of ServletContext objects.

  1、Write a listener,The code is as follows:

package com.web.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
* @ClassName: MyServletContextListener
* @Description: MyServletContextListenerThe class implements the ServletContextListener interface,* therefore, these two actions can be monitored for the creation and destruction of ServletContext objects.*@author: hdb
* @date: 2017-11-9 10:26:16 p.m.**/ 
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContextObject creation ");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContextObject destruction ");
    }
}

  2、Register a listener in a web.xml file

  In the above, we mentioned that in order to monitor the source of the event, the listener must be registered on the source of the event to be able to monitor the action of the event source. In JavaWeb, the registration of the listener is configured in the web.xml file, as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- Register listener --> for monitoring ServletContext objects;<listener>
      <description>ServletContextListenerThe listener < /description><!! - implements the listener class --> of the ServletContextListener interface.<listener-class>com.web.listener.MyServletContextListener</listener-class>
  </listener>
  
</web-app>

  After these two steps, we have completed the writing and registration of the listener, and when the Web server starts, it automatically registers the listener configured in the web.xml to the ServletContext object, so that the developed MyServletContextLi is developed.The Stener listener can monitor the ServletContext object.

  In Servlet3.0, the configuration of listeners can be done directly through the annotation in the code without reconfiguration in web.xml.@WebListener //Note that the following class is a listener

2.4、Monitor the creation and destruction of HttpSession domain objects

  HttpSessionListener Interface is used to monitor the creation and destruction of HttpSession objects.
  When creating a Session, excitesessionCreated (HttpSessionEvent se) Method
  When a Session is destroyed, excitesessionDestroyed (HttpSessionEvent se) Method.

Example: writing a MyHttpSessionListener class,Implement HttpSessionListener interface and monitor the creation and destruction of HttpSession objects.

  1、Write a listener,The code is as follows:

package com.web.listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
* @ClassName: MyHttpSessionListener
* @Description: MyHttpSessionListenerThe class implements the HttpSessionListener interface,* therefore, these two actions can be monitored for the creation and destruction of HttpSession objects.*@author: hdb
* @date: 2017-11-9 11:04:33 p.m.**/ 
public class MyHttpSessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println( se.getSession() + "Created!!! ");
    }

    /* HttpSessionThe destruction time should be allocated in web.xml, as follows:* < session-config>< session-timeout> 1< /seSsion-timeout>< /session-config>This configuration means that session will be destroyed in 1 minutes.*/
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("sessionIt's destroyed! ");
    }
}

  2、Register a listener in a web.xml file

<!--Register listener --> for monitoring HttpSession objects;< listener>< description> HttpSessionListener listener ≪ /description>< listener-class>com.web.listener.MyHttpSessionListener</listener-class>
  </listener>
  <!-- Configuring the destruction time of the HttpSession object -->< session-config><!! - destroy --> after 1 minutes of configuring HttpSession object;< session-timeout> 1< /session-timeout>< /session-config>

  When we access the JSP page, the HttpSession object will be created, and the creation process of the HttpSession object can be observed at HttpSessionListener, and we can write a JSP page to observe the HttpSessThe process of creating a ion object.

As follows: index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>

<!DOCTYPE HTML>
<html>
  <head>
    <title>HttpSessionListenerListeners monitor the creation of HttpSession objects: < /title>< /head>< body>
       Once you access the JSP page, HttpSession is created, and the Id of the created Session is: ${pageContext.session.id}</body>
</html>

The results are as follows:

  

2.5、Monitor the creation and destruction of ServletRequest domain objects

  ServletRequestListenerInterface is used to monitor the creation and destruction of ServletRequest objects.
  RequestWhen the object is created, the listener isrequestInitialized(ServletRequestEvent sre)The method will be called
  RequestWhen the object is destroyed, the listener isrequestDestroyed(ServletRequestEvent sre)The method will be called

  ServletRequestThe time to create and destroy domain objects:
    Creation: users will create request objects at every visit.
    Destruction: at the end of the current visit, the request object will be destroyed.

Example: write a MyServletRequestListener class.Implement ServletRequestListener interface and monitor the creation and destruction of ServletRequest objects.

  1、Write a listener,The code is as follows:

package com.web.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

/**
* @ClassName: MyServletRequestListener
* @Description: MyServletRequestListenerThe class implements the ServletRequestListener interface,* therefore, these two actions can be monitored for the creation and destruction of ServletRequest objects.*@author: hdb
* @date: 2017-11-9 11:50:08 p.m.**/ 
public class MyServletRequestListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println(sre.getServletRequest() + "It's destroyed! ");
        
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println(sre.getServletRequest() + "Created!!! ");
    }
}

  2、Register a listener in a web.xml file

  <!--Register listeners for monitoring ServletRequest objects-->
    <listener>
       <description>ServletRequestListenerMonitor</description>
       <listener-class>com.web.listener.MyServletRequestListener</listener-class>
   </listener>

The results of the test are as follows:

  

  As you can see from the results, users will create request objects on every visit. When the end of the visit, the request object will be destroyed.

2.6、getAttributeThe difference from getParameter

  This part is an extension to JSP and often gets data from JSP or Servlet. So what’s the difference between getAttribute and getParameter?

  1 fromGet the source of the dataFor example:

  getAttribtueThe value of the web container is obtained, such as:

  In Servlet, we set a value through setAttribute, which exists in the container and can be obtained by getAttribute.

  getParameterGets the value that is passed through HTTP, such as such a HTTP request:

http:localhost:8080/test/test.html?username=xingoo

  There are other GET and POST modes that can be obtained through getParameter.

  2 fromAcquired data typeFor example:

  getAttributeThe return is an object, Object.

  getParameterWhat is returned is that the value passed by the form in the front page or behind the HTTP is a string.

2.7、Frequently used listener

    In addition to the above listener session, the following commonly used listeners are built and destroyed by listener.

    1:Listens for the increase and removal of session attributes and the change of attribute values.HttpSessionAttributeListener

    2:Monitor the initialization of the Web context (the server is ready to receive the request) and destroy it.ServletContextListener

    3:Listens for Web context properties to increase, delete, and change attribute values.ServletContextAttributeListener

 

    4:Listening to the creation and destruction of requestServletRequestListener

    5:Listens to the addition, deletion, and change of attribute values of request attributes.ServletRequestAttributeListener

Link of this Article: Listener learning (1)

Leave a Reply

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