In-depth analysis of Java Web Item38-Listener (Listener) quick learning

Source: Internet
Author: User

In-depth analysis of Java Web Item38-Listener (Listener) quick learning
1. Listener Introduction1.1 listener Concept

  

A listener is an object that is used to listen for and process events or state changes on other objects. When the Monitored Objects occur, they take corresponding actions immediately. The listener is actually a common java program that implements a specific interface. This program is used to listen for method calls or attribute changes of another java object. After the above events occur on the Monitored object, the listener immediately executes a method.

1.2 listener case-listener for window Event Listeners
Package me. gacl. listener. demo; import java. awt. frame; import java. awt. event. using wevent; 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 calls a method of the event listener, when this method is called, the event object is passed in. * The developer can obtain the event source through the event object in the listener and perform operations on the event source. */Public static void main (String [] args) {Frame f = new Frame (); f. setSize (400,400); f. setVisible (true); // registers the event listener f. addWindowListener (new WindowListener () {public void windowActivated (WindowEvent e) {} public void windowClosed (WindowEvent e) {}/*** when the window form is closed, the listener WindowListener is listened, * The listener calls the windowClosing method to process the action when the window form is closed */public void windowClosing (WindowEvent e) {// obtain the event source object Frame f = (Frame) e through event object e. getSource (); System. out. println (f + "The form is being closed"); f. dispose ();} public void windowDeactivated (protected wevent e) {} public void windowDeiconified (protected wevent e) {} public void protected wiconified (protected wevent e) {} public void windowOpened) {}});}}
1.3. design an object that can be monitored by another object

We usually write listeners to listen to other objects during development. So if we want to design an object so that this object can be listened to by another object, what should we do, you can design an object according to the strict event processing model. This object can be monitored by other objects. The event processing model involves three components: Event source, event object, and event listener.

The following code designs a Person object based on the event processing model:

Package me. gacl. observer;/*** @ ClassName: Person (event source) * @ Description: design a Person class as the event source. The behavior of objects in this class (such as eating and running) other objects can be listened to * @ author: lone wolf * @ date: 9:26:06 **/public class Person {/*** @ Field: listener * defines a PersonListener variable in the Person class to remember the listener passed in */private PersonListener listener;/*** @ Method: eat * @ Description: design the Person behavior: eat * @ Anthor: Lone Wolf **/public void eat () {if (listener! = Null) {/*** call the doeat method of the listener to listen to the eat (eat) object of the Person class, and pass the Event object Event to the doeat method, * The Event object encapsulates the Event source. this in new Event (this) represents the Event source */listener. doeat (new Event (this) ;}}/*** @ Method: run * @ Description: Design Person behavior: run * @ Anthor: lone Wolf **/public void run () {if (listener! = Null) {/*** call the listener's dorun method to listen to the Person Class Object run (run), and pass the Event object Event to the doeat method, * The Event object encapsulates the Event source. this in new Event (this) represents the Event source */listener. dorun (new Event (this) ;}}/*** @ Method: registerListener * @ Description: this method is used to register the listener * @ Anthor: Lone Wolf ** @ param listener */public void registerListener (PersonListener listener) {this. listener = listener;}/*** @ ClassName: PersonListener (event listener) * @ Description: listener interface of the Person class (event source) * @ author: gu AO Canglang * @ date: 9:28:06 **/interface PersonListener {/*** @ Method: doeat * @ Description: This Method is used to listen to the Person object eat (eat) * When the implementation class implements the doeat method, you can listen to the Person Class Object eat (eat) Action * @ Anthor: gu AO Canglang ** @ param e */void doeat (Event e);/*** @ Method: dorun * @ Description: This Method is used to listen to the Person object run (run) * When the implementation class implements the dorun method, you can listen to the run (run) action of the Person Class Object * @ Anthor: gu AO Canglang ** @ param e */void dorun (Event e);}/*** @ ClassName: Event (Event object) * @ Description: Design Event class, used to encapsulate the Event source * @ author: lone wolf * @ date: 9:37:56 **/class Event {/*** @ Field: source * Event source (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 this design, the Peron class objects 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: lone Wolf ** @ param args */public static void main (String [] args) {// Person p = new Person (); // register the listener for listening to p object behavior p. registerListener (new PersonListener () {// listen to p to eat this behavior public void doeat (Event e) {Person p = e. getSource (); System. out. println (p + "eat");} // listen to p running this behavior public void dorun (Event e) {Person p = e. getSource (); System. out. println (p + "running") ;}}); // p is eating p. eat (); // p running p. run ();}}

Running result:

Me. gacl. observer. Person @ 4a5ab2 is eating
Me. gacl. observer. Person @ 4a5ab2 running

Ii. listener in Java Web 2.1 Basic Concepts

The listener in Java web is a special class defined in the Servlet specification. It is used to listen to the creation and destruction events of domain objects such as ServletContext, HttpSession, and ServletRequest in web applications, and events that listen to the modification of attributes in these domain objects.

2.2. Servlet listener Classification

Multiple types of listeners are defined in the Servlet specification. The event sources used for listening areServletContext,HttpSessionAndServletRequestThese three domain objects
The Servlet specification divides multiple types of listeners into three types for operations on these three objects:

Event Listeners that listen to the creation and destruction of domain objects. Adds and deletes event listeners in the listener domain objects. Listen to the event listener for the status of an object bound to the HttpSession domain. 2.3 listen to the creation and destruction of the ServletContext domain object

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

When a ServletContext object is created, the contextInitialized (ServletContextEvent sce) method is activated.

When the ServletContext object is destroyed, the contextDestroyed (ServletContextEvent sce) method is triggered.

When the ServletContext domain object is created and destroyed:
Create: server startup creates ServletContext for each Web Application
Destroy: Shut down the ServletContext that represents each web application before the server is shut down.

Example: compile a MyServletContextListener class to implement the ServletContextListener interface and listen to the creation and destruction of the ServletContext object.

  1. Compile the listenerThe Code is as follows:

Package me. gacl. web. listener; import javax. servlet. servletContextEvent; import javax. servlet. servletContextListener;/*** @ ClassName: MyServletContextListener * @ Description: MyServletContextListener class implements the ServletContextListener interface. * You can listen to the creation and destruction of the ServletContext object. * @ Author: lone wolf * @ date: 10:26:16 **/public class MyServletContextListener implements ServletContextListener {@ Override public void contextInitialized (ServletContextEvent sce) {System. out. println ("create ServletContext object") ;}@ Override public void contextDestroyed (ServletContextEvent sce) {System. out. println ("ServletContext object destruction ");}}

  2. register the listener in the web. xml file.

As mentioned above, to listen to the event source, you must register the listener to the event source to listen to the action of the event source. In JavaWeb, the listener is registered on the web. the configuration in the xml file is as follows:

 
    
         
       
    
     
Index. jsp
      
        
         
    
     
ServletContextListener listener
                 
    
     
Me. gacl. web. listener. MyServletContextListener
      
   
  

After these two steps, we have completed the compilation and registration of the listener. When the Web server is started, it will automatically put in the web. the listener configured in xml is registered to the ServletContext object, so that the developed MyServletContextListener listener can listen to 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 the HttpSession object.
When a Session is created, the sessionCreated (HttpSessionEvent se) method is activated.
When a Session is destroyed, the sessionDestroyed (HttpSessionEvent se) method is triggered.

Example: compile a MyHttpSessionListener class to implement the HttpSessionListener interface and listen to the creation and destruction of the HttpSession object.

  1. Compile the listenerThe Code is as follows:

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, You can monitor the creation and destruction of the HttpSession object. * @ Author: lone wolf * @ date: 11:04:33 **/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 :*
                
   
    
1
             
  In this way, the session will be destroyed in 1 minute */@ Override public void sessionDestroyed (HttpSessionEvent se) {System. out. println ("the session has been destroyed !! ");}}

  2. register the listener in the web. xml file.

    
        
   
    
HttpSessionListener listener
         
   
    
Me. gacl. web. listener. MyHttpSessionListener
     
       
               
   
    
1
     
  

When we access the jsp page, the HttpSession object will be created. Now we can see the creation process of the HttpSession object in HttpSessionListener. we can write a jsp page to observe the creation process of the HttpSession object.

Index. jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
When you access the JSP page, HttpSession is created. The created Session Id is $ {pageContext. session. id}

The running result is as follows:

2.5 listen to the creation and destruction of the ServletRequest domain object

The ServletRequestListener interface is used to listen to the creation and destruction of the ServletRequest object.
When the Request object is created, the listener's requestInitialized (ServletRequestEvent sre) method will be called
When the Request object is destroyed, the listener's requestDestroyed (ServletRequestEvent sre) method will be called

When the ServletRequest domain object is created and destroyed:
Create: A request object is created for each access.
Destroy: the current access ends, and the request object will be destroyed.

Example: compile a MyServletRequestListener class to implement the ServletRequestListener interface and listen to the creation and destruction of the ServletRequest object.

  1. Compile the listenerThe Code is as follows:

Package me. gacl. web. listener; import javax. servlet. servletRequestEvent; import javax. servlet. servletRequestListener;/*** @ ClassName: MyServletRequestListener * @ Description: MyServletRequestListener class implements the ServletRequestListener interface. * therefore, You can monitor the creation and destruction of the ServletRequest object. * @ Author: lone wolf * @ date: 2014-9-9 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.

    
         
   
    
ServletRequestListener listener
          
   
    
Me. gacl. web. listener. MyServletRequestListener
      
  

The test results are as follows:

You can see from the running results that the request object is created for each access. After the access is completed, the request object is destroyed.

The above is a brief explanation of 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.