Fast learning how to use the Listener (Listener) in Javaweb _java

Source: Internet
Author: User
Tags event listener

First, the listener introduction

1.1, the concept of the listener

 

A listener is an object that is specifically designed to monitor and handle events or state changes that occur on other objects, taking action immediately when the object being monitored occurs. The listener is actually a common Java program that implements a specific interface, which is designed to listen to method calls or property changes to another Java object, and the listener's method is executed immediately after the event that occurs on the listening object.

1.2, Listener Case-Monitor window windows of the event listener

Package Me.gacl.listener.demo;
Import Java.awt.Frame;
Import java.awt.event.WindowEvent;

Import Java.awt.event.WindowListener; public class Demo1 {/** *java event listener *1, event sniffing involves three components: Event source, event object, Event listener * 2, when an action occurs on an event source, it invokes a method of the event listener, and when the method is invoked
   object is passed in, * the developer can take the event source through the event object in the listener, thereby manipulating the event source.
    * * public static void Main (string[] args) {frame f = new Frame ();
    F.setsize (400, 400);

    F.setvisible (TRUE);

      Registering Event Listener F.addwindowlistener (new WindowListener () {public void windowactivated (WindowEvent e) {} public void windowclosed (WindowEvent e) {}/** * when the window form closes it windowlistener this listener is listening to, * listening
        The Windowclosing method handles the action of the Window form closing/public void windowclosing (WindowEvent e) {//Gets the event source object through event object E
        Frame F = (frame) e.getsource ();
        System.out.println (f+ "form is shutting down");
      F.dispose (); The public void windowdeactivated (WindowEvent e) {} is public void WindowdEiconified (WindowEvent e) {} public void windowiconified (WindowEvent e) {} public void Windo
  wopened (WindowEvent e) {}});

 }
}

1.3. Design an object that can be monitored by another object

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 a strict event handling model to design an object, this object can be monitored by other objects, The event-handling model involves three components: the event source, the event object, and the event listener.

Let's design a person object according to the event-handling model as follows:

Package me.gacl.observer; /** * @ClassName: Person (Event Source) * @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 * @author: Aloof Wolf * @date: 2014-  
  9-9 PM 9:26:06 * * * */public class Person {/** * @Field: Listener * Define a Personlistener variable in the person class to remember the listener passing in.

  Private Personlistener listener; /** * @Method: Eat * @Description: Design person's behavior: Eat * @Anthor: Aloof wolf */public void Eat () {if (Listener!= NULL) {/** * calls the listener's Doeat method to listen for a person class object Eat (EAT) This action, passing event object events to the Doeat method, * The event object encapsulates the event source, the T in the new event (this)
    His representative is the event source/listener.doeat (new event (this)); }/** * @Method: Run * @Description: Design person's behavior: Run * @Anthor: Aloof wolf */public void run () {if (LIS Tener!= null) {/** * calls the listener's Dorun method to listen for the Person class object run (run) This action, pass event object events to the Doeat method, * Event object encapsulates the event source, new event
    This represents the event source/Listener.dorun (new event (this)); }/** * @Method: Registerlistener * @Description:This method is used to register listeners listening to the behavior of the Person class object @Anthor: Aloof Wolf * * @param listener/public void Registerlistener (Personlistene
  R listener) {This.listener = listener; }/** * @ClassName: Personlistener (Event listener) * @Description: Listener interface for Design Person class (event source) * @author: Aloof Wolf * @date: 2014-9-9 9:28         : * * */interface Personlistener {/** * @Method: Doeat * @Description: This method is used to monitor the action of the person object eat (EAT)

  When implementing the class implementation Doeat method can be heard the person class object Eat (EAT) This action * @Anthor: Aloof Wolf * * @param E/void Doeat (Event e); /** * @Method: Dorun * @Description: This method is used to monitor the behavior of the person object run (run), * when the implementation class implements the Dorun method, you can listen to the Person class object run (run) this movement

* @Anthor: Aloof Wolf * * @param E/void Dorun (Event e); /** * @ClassName: Events (Event object) * @Description: Design event class to encapsulate event source * @author: Aloof Wolf * @date: 2014-9-9 PM 9:37:56 * * * * class even

  t {/** * @Field: Source * Event Sources (person is the event source) */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 me.gacl.observer;

public class Persontest {

  /**
   * @Method: Main
   * @Description: Test person class
   * @Anthor: Lonely Wolf
   * param args
   */public
  static void Main (string[] args) {
    //person
    p = new Person ();
    Registers listeners listening for P object behavior
    p.registerlistener (new Personlistener () {
      //monitor P eats this behavior public
      void Doeat (Event e) { Person
        p = e.getsource ();
        SYSTEM.OUT.PRINTLN (P + "in Food");
      }
      Monitor p running this behavior public
      void Dorun (Event e) {person
        P = e.getsource ();
        SYSTEM.OUT.PRINTLN (P + "on Run");
      }
    )
    ; P is eating something
    p.eat ();
    P in running
    p.run ();
  }


Run Result:

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

Second, the listener in the Javaweb

2.1. Basic Concepts

The listener in Javaweb is a special class defined in the servlet specification that listens to the creation and destruction events of domain objects such as ServletContext, HttpSession, and ServletRequest in Web applications. And the events that listen for modifications to the properties in these domain objects.

2.2, the servlet listener classification

Multiple types of listeners are defined in the servlet specification, and they are used for listening to the three domain objects of servletcontext,httpsession and ServletRequest, respectively
The servlet specification divides several types of listeners into three types for operations on these three objects:
• Listen for event listeners that are created and destroyed by the domain object itself.
• Listen for an increase in the number of properties in a domain object and a deleted event listener.
• 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 creation and destruction events for ServletContext objects. Classes that implement the Servletcontextlistener interface can monitor the creation and destruction of ServletContext objects.
• Fires the contextinitialized (Servletcontextevent SCE) method when the ServletContext object is created.

• Fires the contextdestroyed (Servletcontextevent SCE) method when the ServletContext object is destroyed.

ServletContext domain object creation and destruction time:
Create: Server startup Create ServletContext for each Web application
Destroy: Shut down the ServletContext that represents each Web application before shutting down the server


Example: Write a Myservletcontextlistener class, implement the Servletcontextlistener interface, monitor the creation and destruction of ServletContext objects

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

Package Me.gacl.web.listener;

Import javax.servlet.ServletContextEvent;
Import Javax.servlet.ServletContextListener;

/**
* @ClassName: Myservletcontextlistener
* @Description: The Myservletcontextlistener class implements the Servletcontextlistener interface,
*         so you can monitor the creation and destruction of the ServletContext object two actions.
* @author: Lonely Wolf
* @date: 2014-9-9 PM 10:26:16 * * * * */Public 
class Myservletcontextlistener Implements Servletcontextlistener {

  @Override public
  void contextinitialized (Servletcontextevent sce) {
    System.out.println ("ServletContext object Creation");
  }

  @Override public
  void contextdestroyed (Servletcontextevent sce) {
    System.out.println ("ServletContext object destroy ");
  }
}

2, register the Listener in the Web.xml file

We mentioned in the above, in order to listen to the event source, you must register the listener to the event source to implement the action of the event source listener, in the Javaweb, 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/" 
  Java ee " 
  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>

 <!--registers listeners listening to ServletContext objects-->
 <listener>
   < Description>servletcontextlistener Listener </description>
   <!--implements the listener class for the Servletcontextlistener interface- >
   <listener-class>me.gacl.web.listener.MyServletContextListener</listener-class>
 < /listener>

</web-app>

After these two steps, we have completed the listener's writing and registering, the Web server at startup, Automatically registers the listener configured in the Web.xml to the ServletContext object, so that the Myservletcontextlistener listener can monitor 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
Fires the sessioncreated (httpsessionevent se) method when creating a session
Fires the sessiondestroyed (httpsessionevent se) method when a session is destroyed.

Example: Write a Myhttpsessionlistener class, implement the Httpsessionlistener interface, monitor the creation and destruction of HttpSession objects

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

Package Me.gacl.web.listener;

Import javax.servlet.http.HttpSessionEvent;
Import Javax.servlet.http.HttpSessionListener;

/**
* @ClassName: Myhttpsessionlistener
* @Description: Myhttpsessionlistener class implements the Httpsessionlistener interface,
*         So the two actions of httpsession object creation and destruction can be monitored.
* @author: Lonely Wolf
* @date: 2014-9-9 PM 11:04:33 * * * * */Public 
class Myhttpsessionlistener Implements Httpsessionlistener {

  @Override public
  void sessioncreated (httpsessionevent se) {
    System.out.println (se.getsession () + "Created!!" ");
  }

  /* HttpSession destruction time needs to be configured in Web.xml, as follows:
   * <session-config>
       <session-timeout>1</ Session-timeout>
     </session-config>
     This configuration means that the session will be destroyed after 1 minutes.
   * *
  @Override
  public void sessiondestroyed (httpsessionevent se) {
    System.out.println (the session was destroyed!!) ");
  }
}

2, register the Listener in the Web.xml file

<!--registers listeners-->
  <listener> <description>httpsessionlistener listeners for HttpSession objects for listening
   </ Description>
   <listener-class>me.gacl.web.listener.MyHttpSessionListener</listener-class>
 </listener>
 <!--Configure HttpSession object's destruction time-->
 <session-config>
   <!-- Configure HttpSession objects after 1 minutes of destruction-->
   <session-timeout>1</session-timeout>
 </session-config>

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

as follows: index.jsp

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

DOCTYPE html>
 
 

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
The requestinitialized (Servletrequestevent sre) method of the listener is invoked when the request object is created
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 on every visit by the user
Destroy: The request object will be destroyed at the end of the current access

Example: Write a Myservletrequestlistener class, implement the Servletrequestlistener interface, monitor the creation and destruction of ServletRequest objects

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

Package Me.gacl.web.listener;

Import javax.servlet.ServletRequestEvent;
Import Javax.servlet.ServletRequestListener;

/**
* @ClassName: Myservletrequestlistener
* @Description: The Myservletrequestlistener class implements the Servletrequestlistener interface,
*         so you can monitor the creation and destruction of the ServletRequest object two actions.
* @author: Lonely Wolf
* @date: 2014-9-9 PM 11:50:08 * * * * */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

<!--registers listeners listening to servletrequest objects-->
  <listener>
    <description> Servletrequestlistener Listeners </description>
    <listener-class> Me.gacl.web.listener.myservletrequestlistener</listener-class>
  </listener>

The test results are as follows:

As you can see from the results of the run, the request object is created every time the user accesses it, and the request object is destroyed when the access is complete.

These are some simple explanations for the listener.

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.