In-depth analysis of JavaWeb Item39-Listener (Listener) learning advanced

Source: Internet
Author: User

In-depth analysis of JavaWeb Item39-Listener (Listener) learning advanced
1. listener for attribute changes in the domain object

The event listener for attribute changes in the domain object is used to listen.ServletContext, HttpSession, HttpServletRequestListener for property change information events in these three objects.
  
The three listener interfaces areServletContextAttributeListener,HttpSessionAttributeListenerAndServletRequestAttributeListenerThe three interfaces define three methods to process added, deleted, and replaced attributes of the Monitored object, the method names of the same event in the three interfaces are identical, but the accepted parameter types are different.

1.1 attributeAdded Method

When an attribute is added to the Monitored object, the web Container calls the attributeAdded method of the event listener to respond. This method receives an event-type parameter, the listener can use this parameter to obtain the domain object that is adding attributes and the attribute object that is saved to the domain.
The complete Syntax of each domain property listener is defined:

 public void attributeAdded(ServletContextAttributeEvent scae) public void attributeReplaced(HttpSessionBindingEvent  hsbe) public void attributeRmoved(ServletRequestAttributeEvent srae)
1.2 attributeRemoved Method

When a property in the Monitored object is deleted, the web Container calls the attributeRemoved method of the event listener to respond.
The complete Syntax of each domain property listener is defined:

public void attributeRemoved(ServletContextAttributeEvent scae) public void attributeRemoved (HttpSessionBindingEvent  hsbe) public void attributeRemoved (ServletRequestAttributeEvent srae)
1.3 attributeReplaced Method

When an attribute in the listener's domain object is replaced, the web Container calls the attributeReplaced method of the event listener to respond.
The complete Syntax of each domain property listener is defined:

public void attributeReplaced(ServletContextAttributeEvent scae) public void attributeReplaced (HttpSessionBindingEvent  hsbe) public void attributeReplaced (ServletRequestAttributeEvent srae)
1.4 examples of ServletContextAttributeListener listeners:

Write the ServletContextAttributeListener listener to listen to changes in the attribute values of objects in the ServletContext domain. The Code is as follows:

Package me. gacl. web. listener; import java. text. messageFormat; import javax. servlet. servletContextAttributeEvent; import javax. servlet. servletContextAttributeListener;/*** @ ClassName: MyServletContextAttributeListener * @ Description: Event listener for attribute change in the ServletContext domain object * @ author: lone wolf * @ date: 10:53:04 **/public class MyServletContextAttributeListener implements ServletContextAttributeListener {@ Override public void attributeAdded (ServletContextAttributeEvent scab) {String str = MessageFormat. format ("added property: {0} to the ServletContext domain object, property value: {1}", scab. getName (), scab. getValue (); System. out. println (str) ;}@ Override public void attributeRemoved (ServletContextAttributeEvent scab) {String str = MessageFormat. format ("delete attribute in the ServletContext domain object: {0}; Attribute Value: {1}", scab. getName (), scab. getValue (); System. out. println (str) ;}@ Override public void attributeReplaced (ServletContextAttributeEvent scab) {String str = MessageFormat. format ("the value of attribute: {0} is replaced in the ServletContext domain object", scab. getName (); System. out. println (str );}}

Register the listener in the web. xml file

  
         
   
    
MyServletContextAttributeListener listener
          
   
    
Me. gacl. web. listener. MyServletContextAttributeListener
      
  

Compile ServletContextAttributeListenerTest. jsp test page

<%@ page language="java" pageEncoding="UTF-8"%>
<% // Add the attribute application to the application domain object. setAttribute ("name", "lone wolf"); // replace the value of the name attribute in the application domain object. setAttribute ("name", "gacl"); // remove the name attribute application from the application domain object. removeAttribute ("name"); %>

The running result is as follows:

  

The running result shows that the ServletContextListener listener successfully monitors the changes in the attribute values in the ServletContext domain object (application.

1.5 Examples of ServletRequestAttributeListener and HttpSessionAttributeListener listeners:

Compile the listener to listen to the changes in the attribute values of the HttpSession and HttpServletRequest domain objects. The Code is as follows: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> Package me. gacl. web. listener; import java. text. messageFormat; import javax. servlet. servletRequestAttributeEvent; import javax. servlet. servletRequestAttributeListener; import javax. servlet. http. httpSessionAttributeListener; import javax. servlet. http. httpSessionBindingEvent; public class implements HttpSessionAttributeListener, ServletRequestAttributeListener {@ Override public void attributeAdded (ServletRequestAttributeEvent srae) {String str = MessageFormat. format ("ServletRequest domain object added property: {0}, property value: {1}", srae. getName (), srae. getValue (); System. out. println (str) ;}@ Override public void attributeRemoved (ServletRequestAttributeEvent srae) {String str = MessageFormat. format ("delete attribute in the ServletRequest domain object: {0}; Attribute Value: {1}", srae. getName (), srae. getValue (); System. out. println (str) ;}@ Override public void attributeReplaced (ServletRequestAttributeEvent srae) {String str = MessageFormat. format ("ServletRequest domain object replaces the value of attribute: {0}", srae. getName (); System. out. println (str) ;}@ Override public void attributeAdded (HttpSessionBindingEvent se) {String str = MessageFormat. format ("attribute: {0} is added to the HttpSession domain object, and the attribute value is: {1}", se. getName (), se. getValue (); System. out. println (str) ;}@ Override public void attributeRemoved (HttpSessionBindingEvent se) {String str = MessageFormat. format ("delete attribute in HttpSession domain object: {0}, attribute value: {1}", se. getName (), se. getValue (); System. out. println (str) ;}@ Override public void attributeReplaced (HttpSessionBindingEvent se) {String str = MessageFormat. format ("the value of attribute: {0} is replaced in the HttpSession domain object", se. getName (); System. out. println (str );}}

Register the listener in the web. xml file

  
        
   
    
MyRequestAndSessionAttributeListener listener
          
   
    
Me. gacl. web. listener. MyRequestAndSessionAttributeListener
      
  

Compile RequestAndSessionAttributeListenerTest. jsp test page

<%@ page language="java" pageEncoding="UTF-8"%>
<% // Add the attribute session to the session domain object. setAttribute ("aa", "bb"); // replace the value of the aa attribute in the session domain object. setAttribute ("aa", "xx"); // remove the aa attribute session from the session domain object. removeAttribute ("aa"); // Add the property request to the request domain object. setAttribute ("aa", "bb"); // replace the value of the aa attribute in the request domain object. setAttribute ("aa", "xx"); // remove the aa attribute request from the request domain object. removeAttribute ("aa"); %>

The running result is as follows:

  

From the running results, we can see that the HttpSessionAttributeListener listener and ServletRequestAttributeListener have successfully listened to changes in the attribute values of the HttpSession domain object and the HttpServletRequest domain object.

2. perceive the event listener bound to the Session

Objects stored in the Session field can be in multiple States: bound (session. setAttribute ("bean", Object) to the Session. removeAttribute ("bean") binding; persists to a storage device as the Session object; recovers from a storage device as the Session object
Two special listener interfaces are defined in the Servlet specification."HttpSessionBindingListener and HttpSessionActivationListener" helps the JavaBean object understand these statuses in the Session domain: classes that implement these two interfaces do not need to be registered in the web. xml file.

2.1. HttpSessionBindingListener Interface

  The JavaBean object that implements the HttpSessionBindingListener interface can detect events that are bound to and deleted from sessions.
When an object is bound to an HttpSession object, the web server calls the void valueBound (HttpSessionBindingEvent event) method of the object.
When an object is unbound from an HttpSession object, the web server calls the void valueUnbound (HttpSessionBindingEvent event) method of the object.

Example:

Package me. gacl. domain; import javax. servlet. http. httpSessionBindingEvent; import javax. servlet. http. httpSessionBindingListener;/*** @ ClassName: JavaBeanDemo1 * @ Description: * The JavaBean object that implements the HttpSessionBindingListener interface can perceive events bound to and deleted from sessions. when an object is bound to an HttpSession object, the web server calls the void valueBound (HttpSessionBindingEvent event) method of the object. When the object is unbound from the HttpSession object, the web server calls the void valueUnbound (HttpSessionBindingEvent event) method of the object * @ author: lone wolf * @ date: 11:14:54 **/public class JavaBeanDemo1 implements HttpSessionBindingListener {private String name; @ Override public void valueBound (HttpSessionBindingEvent event) {System. out. println (name + "added to session");} @ Override public void valueUnbound (HttpSessionBindingEvent event) {System. out. println (name + "kicked out by session");} public String getName () {return name;} public void setName (String name) {this. name = name;} public JavaBeanDemo1 (String name) {this. name = name ;}}

The aforementioned JavaBeanDemo1 javabean implements the HttpSessionBindingListener interface, so this JavaBean object can perceive the two operations bound to and deleted from the Session. The test code is as follows:

<%@ page language="java" pageEncoding="UTF-8"%><%@page import=" me.gacl.domain.JavaBeanDemo1"%>
<% // Bind the javabean object to the Session. setAttribute ("bean", new JavaBeanDemo1 ("lone wolf"); // Delete the Session of the javabean object from the session. removeAttribute ("bean"); %>

The running result is as follows:

  

2.2 HttpSessionActivationListener Interface

  The JavaBean object that implements the HttpSessionActivationListener interface can perceive events that are activated (deserialized) and deactivated (serialized ).
When the javabean object bound to the HttpSession object is deprecated along with the HttpSession object(Serialization)Previously, the web server called the void sessionWillPassivate (HttpSessionEvent event) method of the javabean object. In this way, the javabean object will know that it will be serialized (deactivated) to the hard disk together with the HttpSession object.
When the javabean object bound to the HttpSession object is activated with the HttpSession object(Deserialization)Then, the web server calls the void sessionDidActive (HttpSessionEvent event) method of the javabean object. In this way, the javabean object will know that it will be deserialized (activated) together with the HttpSession object and return to the memory.

Example:

Package me. gacl. domain; import java. io. serializable; import javax. servlet. http. httpSessionActivationListener; import javax. servlet. http. httpSessionEvent;/*** @ ClassName: JavaBeanDemo2 * @ Description: the javabean object and Session are deserialized (activated) to the memory. Passive: the javabean object exists in the Session. When the server serializes the session to the hard disk, if the javabean object in the Session implements the Serializable interface, the server will serialize the javabean object in the session to the hard disk together, this operation that serializes A javabean object and a Session to a hard disk is called as passivation. If the javabean object in the Session does not implement the Serializable interface, the server will first remove the javabean object in the Session that does not implement the Serializable interface, and then serialize (deactivate) the Session) to the hard disk, when the javabean object bound to the HttpSession object will be deactivated with the HttpSession object, the web server calls the void sessionWillPassivate (HttpSessionEvent event) of the javabean object) in this way, the javabean object knows that it will be serialized (deactivated) to the hard disk together with the HttpSession object. When the javabean object bound to the HttpSession object is activated along with the HttpSession object, the web server calls the void sessionDidActive (HttpSessionEvent event) method of the javabean object so that the javabean object can know that it will be deserialized (activated) together with the HttpSession object and return to the memory * @ author: gu AO Canglang * @ date: 11:22:35 **/public class JavaBeanDemo2 implements HttpSessionActivationListener, Serializable {private static final long serialVersionUID = 7589841135210272124L; private String name; @ Override public void sessionWillPassivate (HttpSessionEvent se) {System. out. println (name + "and session are serialized (passive) to the hard disk. The session id is:" + se. getSession (). getId ();} @ Override public void sessionDidActivate (HttpSessionEvent se) {System. out. println (name + "and session are returned from hard disk deserialization (activation) to memory. The session id is:" + se. getSession (). getId ();} public String getName () {return name;} public void setName (String name) {this. name = name;} public JavaBeanDemo2 (String name) {this. name = name ;}}

In order to observe the process that the javabean object bound to the HttpSession object is inactivated together with the HttpSession object to the hard disk and reactivated back to the memory from the hard disk, we need to use the tomcat server to help us complete the passivation and activation process of the HttpSession object. The specific practices are as follows:

Create a context. xml file in the WebRoot \ META-INF folder, as shown below:

  

The content of the context. xml file is as follows:


       
        
         
    
    
  

One minute after being configured in the context. xml file, the HttpSession object will be deactivated to a gacl folder on the local hard disk.

The jsp test code is as follows:

<%@ page language="java" pageEncoding="UTF-8"%><%@page import="me.gacl.domain.JavaBeanDemo2"%>
When you access the JSP page, HttpSession is created. The created Session Id is $ {pageContext. session. id} <% Session. setAttribute ("bean", new JavaBeanDemo2 ("lone wolf"); %>

Access this jsp page, the server will immediately create an HttpSession object, and thenJavaBean object that implements the HttpSessionActivationListener InterfaceBound to the session object. This jsp page is not accessed again after one minute, so the server will automatically deactivate (serialize) The HttpSession object to the hard disk,

  
  
We canwork\Catalina\localhost\JavaWeb_Listener_20140908\gaclFind the session serialized to local storage under the folder, as shown in:

  

When the Jsp page is accessed again, the server automatically reactivates (deserializes) The HttpSession object on the hard disk and returns it to the memory. The running result is as follows:

  

The listener Technology in Java Web development has so much content. In normal work, the listener technology is used in Java Web project development. Therefore, you must master this technology.

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.