1. Monitor introduction
1.1. The concept of listener
A listener is an object specially used to listen and process events or state changes occurring on other objects. When a situation occurs in the monitored object, corresponding actions will be taken immediately. A listener is actually an ordinary java program that implements a specific interface. This program is specifically used to listen for method calls or property changes of another java object. When the above event occurs in the object being listened to, a certain method of the listener is executed immediately.
1.2. Listener case--event listener listening to window window
package me.gacl.listener.demo;import java.awt.Frame;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;public class Demo1 { /** *java event listening mechanism*1. Event listening involves three components: event source, event object, event listener*2. When an action occurs on the event source, it will call a method of the event listener and pass the event object in when calling the method. * Developers can get the event source through the event object in the listener, thereby operating on 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 is closed, the WindowListener listener will be heard, * The listener will call the windowClosing method to handle the actions when the window form is closed*/ public void windowClosing(WindowEvent e) { //Get the event source object through event object eFrame f = (Frame) e.getSource(); System.out.println(f+"Form is closing"); f.dispose(); } public void windowDeactivated(WindowEvent e) { } public void windowDeiconized(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } }); }}1.3. Design an object that can be listened to by other objects
When we are doing development, we write listeners to monitor other objects. So what should we do if we want to design an object so that this object can be listened to by other objects? We can design an object according to a strict event processing model, and this object can be listened to by other objects. The event processing model involves three components: event source, event object, and event listener.
Let’s design a Person object according to the event processing model. The specific code is as follows:
package me.gacl.observer;/*** @ClassName: Person(event source)* @Description: Design a Person class as the event source. The behavior of the objects of this class (such as eating, running) can be listened to by other objects* @author: Lonely Canglang* @date: 2014-9-9 9:26:06 pm**/ public class Person { /** * @Field: listener * Define a PersonListener variable in the Person class to remember the passed listener*/ private PersonListener listener; /** * @Method: eat * @Description: Design Person's behavior: eat * @Anthor: The lone and arrogance* */ public void eat() { if (listener != null) { /** * Call the listener's doeat method to listen to the Person class object eat(eat) action, passing the event object to the doeat method, * The event object encapsulates the event source, and this in new Event(this) represents the event source*/ listener.doeat(new Event(this)); } } /** * @Method: run * @Description: Design Person's behavior: Run* @Anthor: The lone and arrogance* */ public void run() { if (listener != null) { /** * Call the dorun method of the listener to listen for the Person class object run(run) action, and pass the event object event event to the doeat method. * The event object encapsulates the event source, and this in new Event(this) represents the event source*/ listener.dorun(new Event(this)); } } /** * @Method: registerListener * @Description: This method is used to register a listener that listens on the behavior of Person class objects* @Anthor: The aloof wolf* * @param listener */ public void registerListener(PersonListener listener) { this.listener = listener; }}/*** @ClassName: PersonListener (event listener)* @Description: Design the listener interface for Person class (event source)* @author: Lonely Canglang* @date: 2014-9-9 9:28:06 pm**/ interface PersonListener { /** * @Method: doeat * @Description: This method is used to monitor the behavior action of Person object eat (eat). * When the implementation class implements the doeat method, you can monitor the action of Person class object eat (eat)* @Anthor: Lonely Canglang* * @param e */ void doeat(Event e); /** * @Method: dorun * @Description: This method is used to listen to the behavior of Person object run(run). * When the implementation class implements the dorun method, you can listen to the action of Person class object run(run)* @Anthor:克克* * @param e */ void dorun(Event e);}/*** @ClassName: Event(event object)* @Description: Design event class to encapsulate event source* @author:克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克克� Event(Person source) { this.source = source; } public Person getSource() { return source; } public void setSource(Person source) { this.source = source; }}After such a design, objects of Peron class can be listened to by other objects. The test code is as follows:
package me.gacl.observer;public class PersonTest { /** * @Method: main * @Description: Test Person class* @Anthor: The arrogant wolf* * @param args */ public static void main(String[] args) { // Person p = new Person(); //Register the listener that listens for the behavior of p objects p objects p.registerListener(new PersonListener() { // Listen to p eating behavior public void doeat(Event e) { Person p = e.getSource(); System.out.println(p + "Eating"); } // Listen to p running public void dorun(Event e) { Person p = e.getSource(); System.out.println(p + "Eating"); } }); //p eating p.eat(); //p running p.run(); }}Running results:
me.gacl.observer.Person@4a5ab2 is eating me.gacl.observer.Person@4a5ab2 is running
2. Listeners in JavaWeb
2.1. Basic concepts
Listeners in JavaWeb are a special class defined in the Servlet specification. They are used to listen for creation and destruction events of domain objects such as ServletContext, HttpSession and ServletRequest in web applications, as well as to listen for events in which properties in these domain objects are modified.
2.2. Classification of Servlet Listeners
There are multiple types of listeners defined in the Servlet specification. The event sources used for listening are ServletContext, HttpSession and ServletRequest. The Servlet specification divides multiple types of listeners into three types for operations on these three objects:
• Event listener that listens to the creation and destruction of the domain object itself.
• Event listener that listens for adding and deleting properties in domain objects.
• An event listener that listens to the status of an object in the HttpSession domain.
2.3. Listen to the creation and destruction of ServletContext domain objects
The ServletContextListener interface is used to listen for the creation and destruction events of ServletContext objects. All classes that implement the ServletContextListener interface can listen for the creation and destruction of ServletContext objects.
• When the ServletContext object is created, the contextInitialized (ServletContextEvent scet) method is fired.
• When the ServletContext object is destroyed, the contextDestroyed(ServletContextEvent scet) method is activated.
•Time for creating and destroying ServletContext domain objects:
Create: Server startup creates ServletContext for each web application
Destruction: Close the ServletContext representing each web application before the server is closed.
Example: Write a MyServletContextListener class, implement the ServletContextListener interface, listen to the creation and destruction of ServletContext objects
1. Write a listener with the following code:
package me.gacl.web.listener;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;/*** @ClassName: MyServletContextListener* @Description: The MyServletContextListener class implements the ServletContextListener interface, * Therefore, you can listen for the creation and destruction of the ServletContext object. * @author: The Proud Wolf* @date: 2014-9-9 10:26:16 pm**/ public class MyServletContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent scet) { System.out.println("ServletContext object creation"); } @Override public void contextDestroyed(ServletContextEvent scet) { System.out.println("ServletContext object destruction"); }}2. Register the listener in the web.xml file
We mentioned above that in order to listen for event sources, you must register the listener to the event source to monitor the action of the event source. In JavaWeb, the listening registration 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 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 a listener for listening to ServletContext objects --> <listener> <description>ServletContextListener listener</description> <!--Receiver class that implements the ServletContextListener interface --> <listener-class>me.gacl.web.listener.MyServletContextListener</listener-class> </listener></web-app>
After these two steps, we have completed the writing and registration of the listener. When the web server starts, it will automatically register the listener configured in web.xml to the ServletContext object. In this way, the developed MyServletContextListener listener can listen on the ServletContext object.
2.4. Listen to the creation and destruction of HttpSession domain objects
The HttpSessionListener interface is used to listen to the creation and destruction of HttpSession objects. When creating a Session, the sessionCreated (HttpSessionEvent se) method is activated when destroying a Session, and the sessionDestroyed (HttpSessionEvent se) method is activated.
Example: Write a MyHttpSessionListener class, implement the HttpSessionListener interface, and listen to the creation and destruction of HttpSession objects
1. Write a listener with the following code:
package me.gacl.web.listener;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;/*** @ClassName: MyHttpSessionListener* @Description: The MyHttpSessionListener class implements the HttpSessionListener interface, * Therefore, the two actions of creating and destroying the HttpSession object can be listened to. * @author: The Lonely Canglang* @date: 2014-9-9 11:04:33 pm**/ public class MyHttpSessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent se) { System.out.println( se.getSession() + "Created!!"); } /* The destruction time of HttpSession needs to be configured in web.xml, as follows: * <session-config> <session-timeout>1</session-timeout> </session-config> This configuration means that the session is destroyed after 1 minute*/ @Override public void sessionDestroyed(HttpSessionEvent se) { System.out.println("session was destroyed!!"); }}2. Register the listener in the web.xml file
<!--Register listener for listening for HttpSession objects --> <listener> <description>HttpSessionListener listener</description> <listener-class>me.gacl.web.listener.MyHttpSessionListener</listener-class> </listener> <!--Configure the time to destroy the HttpSession object --> <session-config> <!--Configure the destruction time of the HttpSession object --> <session-config> <!--Configure the destruction of the HttpSession object 1 minute later-> <session-timeout>1</session-timeout> </session-config>
When we access the jsp page, the HttpSession object will be created. At this time, we can observe the creation process of the HttpSession object in the HttpSessionListener. We can write a jsp page to observe the creation process of the HttpSession object.
As follows: index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %><!DOCTYPE HTML><html> <head> <title>HttpSessionListener listener listens to the creation of HttpSession object</title> </head> <body> Once you access the JSP page, HttpSession is created. The ID of the created Session is: ${pageContext.session.id} </body></html>The operation results are as follows:
2.5. Listen to the creation and destruction of ServletRequest domain objects
When the ServletRequestListener interface is used to listen to the creation and destruction of the ServletRequest object, the requestInitialized(ServletRequestEvent sre) method of the listener will be called. When the Request object is destroyed, the requestDestroyed(ServletRequestEvent sre) method of the listener will be called.
ServletRequest domain object creation and destruction timing:
Create: Every time the user visits, the request object will be created, the request object will be destroyed: the current access is over, the request object will be destroyed.
Example: Write a MyServletRequestListener class, implement the ServletRequestListener interface, listen to the creation and destruction of ServletRequest objects
1. Write a listener with the following code:
package me.gacl.web.listener;import javax.servlet.ServletRequestEvent;import javax.servlet.ServletRequestListener;/*** @ClassName: MyServletRequestListener* @Description: The MyServletRequestListener class implements the ServletRequestListener interface, * Therefore, you can listen for the creation and destruction of the ServletRequest object. * @author: The Proud Wolf* @date: 2014-9-9 11:50:08 pm**/ public class MyServletRequestListener implements ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent sre) { System.out.println(sre.getServletRequest() + "Destroyed!!"); } @Override public void requestInitialized(ServletRequestEvent sre) { System.out.println(sre.getServletRequest() + "Created!!"); }}2. Register the listener in the web.xml file
<!--Register listener for listening to ServletRequest object--> <listener> <description>ServletRequestListener listener</description> <listener-class>me.gacl.web.listener.MyServletRequestListener</listener-class> </listener>
The test results are as follows:
From the run result, we can see that the user creates a request object every time he accesses, and the request object will be destroyed after the access is completed.
The above is a brief explanation of the listener.