Javaweb Learning Summary (44)--Listener (Listener) Learning

Source: Internet
Author: User
Tags in domain

Javaweb Learning Summary (44)--Listener (Listener) learning one, Listener Introduction 1.1, the concept of listeners

  

A listener is an object that listens to and handles events or state changes that occur on other objects and takes action immediately when the object being monitored occurs. A listener is actually a generic Java program that implements a particular interface, which is specifically designed to listen to a method call or property change of another Java object, which is immediately executed by a listener when the event has occurred.

1.2. Listener case--Listen to the event Listener in Windows window
 1 package Me.gacl.listener.demo; 2 3 Import Java.awt.Frame; 4 Import java.awt.event.WindowEvent; 5 Import Java.awt.event.WindowListener; 6 7 public class Demo1 {8 9/**10 *java Event Monitoring Mechanism 11 * 1, event monitoring involves three components: Event source, event object, Event listener 12 * 2, when an action occurs on an event source, it A method that invokes the event listener and passes the event object in when the method is called, 13 * The developer can get the event source through the event object in the listener, thereby manipulating the event source. */15 public static void Main (string[] args) {frame F = new frame (); F.setsize ( F.setvisible (True); 20 21//Register Event Listener F.addwindowlistener (new WindowListener ()  {windowactivated public void (WindowEvent e) {}27- void windowclosed (WindowEvent e) {29 30}31 32/**33 * When the window form is closed Will windowlistener this listener, 34 * The listener will call the Windowclosing method to handle the action of the window form closed */36 public VO              ID windowclosing (windowevent e) {37   Gets the event source object through the event object E: Frame f = (Frame) e.getsource (), System.out.println (f+ "Form Closing"); 4                 0 f.dispose ();}42 public void windowdeactivated (WindowEvent e) {44 }46 windowdeiconified (WindowEvent e) {48 49} The public void windowiconified (WindowEvent e) {}54 void windowopened (WindowEvent e) {56 57}58}); 59}60}
1.3. Design an object that can be monitored by other objects

We usually do development, we are writing listeners to listen to other objects, then if we want to design an object, so that the object can be monitored by other objects and how to do it, you can follow the strict event processing model to design an object, this object can be monitored by other objects, The event processing model involves three components: an event source, an event object, and an event listener.

Let's follow the event- handling model to design a person object with the following code:

  1 package me.gacl.observer;   2 3/** 4 * @ClassName: Person (Event source) 5 * @Description: Design a person class as an event source, the behavior of objects of this class (such as eating, running) can be monitored by other objects 6 * @author: Aloof Wolf          7 * @date: 2014-9-9 PM 9:26:06 8 * 9 * * public class Person {/** * @Field: Listener 13 * Define a Personlistener variable in the person class to remember the listener that is passed in. */the private Personlistener listener;     /** * @Method: Eat * @Description: Design person behavior: Eat a * @Anthor: Aloof Wolf 21 * 22 * * 23 public void Eat () {listener! = null) {25/** 26 * Calls the listener's Doeat method to listen for the Person class object eat (Eat This action, which passes event object events to the Doeat method, 27 * Event object encapsulates the event source, and this in new event represents the event source. Istener.doeat (New Event (this));     + 37}/** * @Method: Run * @Description: Design person's behavior: run a few * @Anthor: aloof and pale Wolf (blue)-----------           * * * * * the public void run () {listener = null) {41/** 42   * Call Listener's Dorun method to listen to the Person class object run (run) This action, the event object is passed to the Doeat method, 43 * Event object encapsulates the event source, the new event (this) represents the event source 4 4 */Listener.dorun (new Event (this)); /** * @Method: Registerlistener * @Description: This method is used to register the listener for the behavior of the person class object. Listener * @Anthor: Lonely Wolf * * @param listener * * * * * * * * * * * * (Personlistener Listener) {This.listener = listener; +) (/**) * @ClassName: Personlistener (Event listener) * @Des  Cription: Listener interface for designing the person Class (event source) * @author: Aloof Wolf * @date: 2014-9-9 PM 9:28:06 * * * * * interface Personlistener { /** * @Method: Doeat * @Description: This method is used to listen to the person object eat (EAT) This behavior action, 73 * when the implementation The class implements the Doeat method to listen to the Person class object Eat (EAT) This action, "@Anthor: Aloof and lonely wolf * * * @param e * * * * * * * * (Event E ); /** Bayi * @Method: Dorun * @Description: This method is used to monitor the personObject Run (Run) This behavior action, 83 * When the implementation class implements the Dorun method, it is possible to hear the person class object run (run) This action is a * @Anthor: Aloof Wolf 85 * 86 * @ Param e * */Dorun void (Event e); /** * @ClassName: Event Object 94 * @Description: Design event class to encapsulate event source * @author: Aloof Wolf * @date: 2014-9-9 Next Noon 9:37:56 * 98 * * * * * * * * * * 101/**102 * @Field: source103 * Event Source (person is the event source) 104 */ source;106 Private Person-107 public event () {108 109}110 111 public event (person source) {11     2 This.source = source;113}114 public Person GetSource () {$ return source;117}118 119 public void SetSource (person source) {This.source = source;121}122}

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

1 package me.gacl.observer; 2  3 public class Persontest {4  5     /** 6      * @Method: Main 7      * @Description: Test Person Class 8      * @Anthor: Aloof Pale Wolf 9      *10      * @param args11      */12 public     static void Main (string[] args) {         //14 person         p = new P Erson ();         the listener that registers the behavior of the listener P         p.registerlistener (new Personlistener () {             //Listen P eat This behavior             public void Doeat (Event e) {The person                 P = e.getsource ();                 System.out.println (P + "eating");             }22             // Monitor P Run this behavior of the public             void Dorun (Event e) {The person                 P = e.getsource ();                 System.out.println (P + "in Running"); 26< C25/>}27         });         //p is eating         p.eat ();         //p is running         p.run ();     }33}

Operation Result:

ME.GACL.OBSERVER.PERSON@4A5AB2 is eating.
ME.GACL.OBSERVER.PERSON@4A5AB2 is running.

Second, javaweb in the Listener 2.1, the basic concept

The listener in Javaweb is a special class defined in the servlet specification that listens to the creation and destruction events of ServletContext, HttpSession, and ServletRequest domain objects in a Web application. and listening for events in which the properties in these domain objects have been modified.

2.2, the servlet listener classification

Several types of listeners are defined in the servlet specification, which are used to listen for the event sources ServletContext,HttpSession , and servletrequest , respectively, of three domain objects
The servlet specification also divides several types of listeners into three types for operations on these three objects:

    1. Listens for event listeners that are created and destroyed by the domain object itself.
    2. Listens for added and deleted event listeners for properties in domain objects.
    3. Listens for event listeners that are bound to the state of an object in the HttpSession domain.
2.3. Monitoring the creation and destruction of ServletContext domain objects

The Servletcontextlistener interface is used to listen for ServletContext object creation and destruction events. Classes that implement the Servletcontextlistener interface can listen to the creation and destruction of ServletContext objects.

The contextinitialized (Servletcontextevent SCE) method is fired when the ServletContext object is created.

The contextdestroyed (Servletcontextevent SCE) method is fired when the ServletContext object is destroyed.

ServletContext domain object creation and destruction time:
Create: Server start create servletcontext for each web App
Destroy: Close the ServletContext on behalf of each Web application before the server shuts down

Example: Writing a Myservletcontextlistener class, implementing the Servletcontextlistener interface, monitoring the creation and destruction of ServletContext objects

1, write the Listener , the code is as follows:

1 package Me.gacl.web.listener; 2  3 import javax.servlet.ServletContextEvent; 4 import Javax.servlet.ServletContextListener; 5  6/** 7 * @ Classname:myservletcontextlistener 8 * @Description: Myservletcontextlistener class implements Servletcontextlistener interface, 9 *                 Therefore, the creation and destruction of the ServletContext object can be monitored for two actions. Ten * @author: Lonely Wolf * @date: 2014-9-9 PM 10:26:1612 *13 * * * public class Myservletcontextlistener implements Servletcont Extlistener {@Override17 public     void contextinitialized (Servletcontextevent sce) {         System.out.println ("ServletContext object Creation"),     }20 @Override22 public     void contextdestroyed ( Servletcontextevent SCE) {         System.out.println ("ServletContext object Destruction");     }25}

  2. Registering listeners in the Web. xml file

As we mentioned in the above, to listen to the source of the event, you must register the listener to the event source to enable monitoring of the event source's behavior, in Javaweb, the registration of the listener is configured in the Web. xml file, as follows:

1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <web-app version= "3.0"  3     xmlns= "http://java.sun.com/xml/ Ns/javaee "  4     xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "  5     xsi:schemalocation=" http ://java.sun.com/xml/ns/javaee  6     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "> 7   < Display-name></display-name>     8   <welcome-file-list> 9     <welcome-file> index.jsp</welcome-file>10   </welcome-file-list>11   <!-- Registering listeners for listening on ServletContext objects-->13   <listener>14       <description>servletcontextlistener Listener </description>15       <!--implements the listener class for the Servletcontextlistener interface-->16       <listener-class> me.gacl.web.listener.myservletcontextlistener</listener-class>17   </listener>18   </ Web-app>

After these two steps, we completed the listener writing and registration, the Web server at startup, The listener configured in Web. XML is automatically registered to the ServletContext object, so that a well-developed Myservletcontextlistener listener can listen to the ServletContext object.

2.4. Monitoring the creation and destruction of HttpSession domain objects

Httpsessionlistener interface for monitoring the creation and destruction of HttpSession objects
When creating a session, the sessioncreated (httpsessionevent se) method is fired
Fires the sessiondestroyed (httpsessionevent se) method when a session is destroyed.

Example: Writing a Myhttpsessionlistener class, implementing the Httpsessionlistener interface, monitoring the creation and destruction of HttpSession objects

1, write the Listener , the code is as follows:

1 package Me.gacl.web.listener; 2  3 import javax.servlet.http.HttpSessionEvent; 4 import Javax.servlet.http.HttpSessionListener; 5  6/** 7 * @ Classname:myhttpsessionlistener 8 * @Description: Myhttpsessionlistener class implements Httpsessionlistener interface, 9 *                 Therefore, the creation and destruction of the HttpSession object can be monitored for two actions. Ten * @author: Lonely Wolf * @date: 2014-9-9 PM 11:04:3312 *13 * * * public class Myhttpsessionlistener implements Httpsessionlis tener {@Override17 public     void sessioncreated (httpsessionevent se) {         System.out.println ( Se.getsession () + "created!! ");     }20     //HttpSession The destruction time needs to be configured in Web. XML, as follows:      * <session-config>23               < Session-timeout>1</session-timeout>24           </session-config>25           This configuration means that the session will be destroyed in 1 minutes. 26      */27     @Override28 public     void sessiondestroyed (httpsessionevent se) {         System.out.println (" The session was destroyed!! ");     }31}

2. Registering listeners in the Web. xml file

1  <!--Register Listener for HttpSession objects--2    <listener> 3       <description> Httpsessionlistener Listener </description> 4       <listener-class> Me.gacl.web.listener.myhttpsessionlistener</listener-class> 5   </listener> 6   <!-- Configure the HttpSession object's destruction time--7   <session-config> 8       <!--Configure HttpSession object 1 minutes after destruction--9       < Session-timeout>1</session-timeout>10   </session-config>

When we visit the JSP page, the HttpSession object is created, and at this point we can observe the creation of the HttpSession object in Httpsessionlistener, and we can write a JSP page to observe the HttpSession object creation process.

as follows: index.jsp

1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2  3 <! DOCTYPE html> 4 

The results of the operation are as follows:

  

2.5. Monitoring the creation and destruction of ServletRequest domain objects

Servletrequestlistener interface for monitoring the creation and destruction of ServletRequest objects
When the request object is created, the Listener's requestinitialized (Servletrequestevent sre) method is called
When the request object is destroyed, the listener's requestdestroyed (Servletrequestevent sre) method is called

ServletRequest domain object creation and destruction time:
Create: The Request object is created every time the user accesses
Destroy: The request object will be destroyed at the end of the current visit

Example: Writing a Myservletrequestlistener class, implementing the Servletrequestlistener interface, monitoring the creation and destruction of ServletRequest objects

1, write the Listener , the code is as follows:

1 package Me.gacl.web.listener; 2  3 import javax.servlet.ServletRequestEvent; 4 import Javax.servlet.ServletRequestListener; 5  6/** 7 * @ Classname:myservletrequestlistener 8 * @Description: Myservletrequestlistener class implements Servletrequestlistener interface, 9 *                 Therefore, the creation and destruction of the ServletRequest object can be monitored for two actions. Ten * @author: Lonely Wolf * @date: 2014-9-9 PM 11:50:0812 *13 * * * public class Myservletrequestlistener implements Servletrequ Estlistener {@Override17 public     void requestdestroyed (Servletrequestevent sre) {         System.out.println (Sre.getservletrequest () + "Destroyed!! "),     }21     @Override23 public     void requestinitialized (Servletrequestevent sre) {         System.out.println (Sre.getservletrequest () + "created!! ");     }26}

2. Registering listeners in the Web. xml file

1  <!--Register Listener listeners for ServletRequest objects-->2    <listener>3       <description> Servletrequestlistener Listener </description>4       <listener-class> Me.gacl.web.listener.myservletrequestlistener</listener-class>5   </listener>

The test results are as follows:

  

As you can see from the running results, the request object is created every time the user accesses, and when the access is finished, the request object is destroyed.

These are some simple explanations for the listener.

Javaweb Learning Summary (44)--Listener (Listener) Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.