Javaweb Learning Summary (45)--Listener (Listener) Learning Two

Source: Internet
Author: User
Tags event listener session id object object tomcat server

A listener that listens for changes to properties in a domain object

The event listener for the change of properties in a domain object is the listener used to listen for ServletContext, HttpSession, HttpServletRequest property Change information events in these three objects.
These three listener interfaces are Servletcontextattributelistener, Httpsessionattributelistener and Servletrequestattributelistener, respectively, Each of the three interfaces defines three methods to handle the addition, deletion, and substitution of the attributes in the Listener object, the same event in the three interfaces corresponding to the same method name, except that the accepted parameter types are different.

1.1. Attributeadded method

When an attribute is added to the listener, the Web container responds with the Attributeadded method that invokes the event listener, which receives an event type parameter that the listener can use to obtain the domain object that is increasing the property and the Property object that is saved to the domain
The complete syntax in each domain property listener is defined as:

1 public void attributeadded (Servletcontextattributeevent scae) 2 public void attributereplaced ( Httpsessionbindingevent  hsbe) 3 public void attributermoved (Servletrequestattributeevent srae)
1.2. Attributeremoved method

The Web container invokes the event listener's Attributeremoved method to respond when one of the properties in the Listener object is deleted
The complete syntax in each domain property listener is defined as:

1 public void attributeremoved (Servletcontextattributeevent scae) 2 public void attributeremoved ( Httpsessionbindingevent  hsbe) 3 public void attributeremoved (Servletrequestattributeevent srae)
1.3. Attributereplaced method

When a property in the listener's domain object is replaced, the Web container invokes the event listener's attributereplaced method to respond
The complete syntax in each domain property listener is defined as:

1 public void attributereplaced (Servletcontextattributeevent scae) 2 public void attributereplaced ( Httpsessionbindingevent  hsbe) 3 public void attributereplaced (Servletrequestattributeevent srae)
1.4. Servletcontextattributelistener Listener Example:

Write the Servletcontextattributelistener listener to listen for changes in the property values of the ServletContext domain object, as follows:

1 package Me.gacl.web.listener; 2 3 Import Java.text.MessageFormat; 4 5 Import Javax.servlet.ServletContextAttributeEvent; 6 Import Javax.servlet.ServletContextAttributeListener; 7 8/** 9 * @ClassName: MYSERVLETCONTEXTATTRIBUTELISTENER10 * @Description: Event listener for changes to properties in ServletContext domain object one by one * @author: Aloof Pale Wolf * @date: 2014-9-11 10:53:0413 *14 */public class Myservletcontextattributelistener IMPLEMENTS16Servletcontextattributelistener{@Override19 public void attributeadded (Servletcontextattributeevent scab) {a String str =messagefo                 Rmat.format (ServletContext) added attribute: {0}, property value is: {1} ", Scab.getname () 23 , Scab.getvalue ()), System.out.println (str),}26 @Override28 public void attributeremoved (Servle Tcontextattributeevent scab) {The attribute is removed from String str =messageformat.format (ServletContext domain object: {0}, genus The sex value is: {1} ", Scab.getname (), Scab.getvalue ()), System.out.println (str); 34} @Override37 public void attributereplaced (Servletcontextattributeevent scab) {$ String str =message Format.format ("ServletContext" replaces the attribute in the Field object: {0} of the value "Scab.getname"); println (str); 42}43}

Registering listeners in the Web. xml file

1  <listener>2       <description>myservletcontextattributelistener listener </description>3       <listener-class>me.gacl.web.listener.myservletcontextattributelistener</listener-class>4   </ Listener>

Writing the servletcontextattributelistenertest.jsp test page

1 <%@ page language= "java" pageencoding= "UTF-8"%> 2 <! DOCTYPE html> 3 

The results of the operation are as follows:

  

As you can see from the running results, the Servletcontextlistener listener successfully monitors the changes in the property values in the ServletContext domain object (application).

1.5. Examples of Servletrequestattributelistener and Httpsessionattributelistener listeners:

Write listeners to listen for changes in the property values of HttpSession and HttpServletRequest domain objects, with the following code:

 1 package Me.gacl.web.listener; 2 3 Import Java.text.MessageFormat; 4 5 Import Javax.servlet.ServletRequestAttributeEvent; 6 Import Javax.servlet.ServletRequestAttributeListener; 7 Import Javax.servlet.http.HttpSessionAttributeListener; 8 Import javax.servlet.http.HttpSessionBindingEvent; 9 public class Myrequestandsessionattributelistener Implements11 Httpsessionattributelistener, Servletrequestat Tributelistener {@Override14 public void attributeadded (Servletrequestattributeevent srae) {Strin                 G str =messageformat.format (servletrequest) added attribute: {0}, property value is: {1} ", Srae.getname () 18 , Srae.getvalue ()); System.out.println (str),}21 @Override23 public void Attribu Teremoved (servletrequestattributeevent srae) {String str =messageformat.format (servletreque Delete attribute in St domain object: {0}, property value is: {1} "Srae.getname", Srae.getvalue ()); 28         System.out.println (str);}30 @Override32 public void attributereplaced (Servletrequestattributeev                 Ent srae) {=messageformat.format: The value of {0} has been replaced with a property in the ServletRequest domain object "35 , Srae.getname ()), System.out.println (str), PNS}38 @Override40 public void attributeadded (httpses                  Sionbindingevent se) {attribute: {0}, attribute value: {1} ' 43 ' in =messageformat.format String str httpsession domain object , Se.getname (), Se.getvalue ()), System.out.println (str),}47 @Ove                 rride49 public void attributeremoved (httpsessionbindingevent se) {String str =messageformat.format (51         "HttpSession domain Object Delete attribute: {0}, property value is: {1}", Se.getname (), Se.getvalue ()); 54         System.out.println (str),}56 @Override58 public void attributereplaced (Httpsessionbindingevent se) {59 String Str =messaGeformat.format ("HttpSession" replaces the attribute in the domain object: {0} of the value "Se.getname"); System.out.pri Ntln (str); 63}64}

Registering listeners in the Web. xml file

1  <listener>2       <description>myrequestandsessionattributelistener listener </description>3       <listener-class>me.gacl.web.listener.myrequestandsessionattributelistener</listener-class>4   </listener>

Writing the requestandsessionattributelistenertest.jsp test page

1 <%@ page language= "java" pageencoding= "UTF-8"%> 2 <! DOCTYPE html> 3 

The results of the operation are as follows:

  

As you can see from the running results, Httpsessionattributelistener listeners and Servletrequestattributelistener successfully monitor the change of property values for HttpSession domain objects and HttpServletRequest domain objects 。

Second, the sense session binding event listener

Objects saved in the session field can have several states: bindings (Session.setattribute ("Bean", "object") to the session, and the Session field (Session.removeattribute (" Bean ")) bind; persist to a storage device with the session object; recover from a storage device with session object
The Servlet specification defines two special listener interfaces "Httpsessionbindinglistener and Httpsessionactivationlistener" to help JavaBean Object to understand these states in the session domain: the classes that implement both 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 perceive events that are bound to the session and deleted by the session.
When an object is bound to a HttpSession object, the Web server calls the object's void Valuebound (Httpsessionbindingevent event) method
When the object is unbound from the HttpSession object, the Web server calls the object's void Valueunbound (Httpsessionbindingevent event) method

Example:

1 package me.gacl.domain; 2 3 Import javax.servlet.http.HttpSessionBindingEvent; 4 Import Javax.servlet.http.HttpSessionBindingListener; 5 6/** 7 * @ClassName: JAVABEANDEMO1 8 * @Description: 9 * JavaBean object that implements the Httpsessionbindinglistener interface can perceive that it is bound to Sess     Ion and events removed from session 10 when an object is bound to a HttpSession object, the Web server calls the object's void Valuebound (Httpsessionbindingevent event) Method 11  When the object is unbound from the HttpSession object, the Web server calls the object's void Valueunbound (Httpsessionbindingevent event) method. * @author: Lonely Wolf * @date: 2014-9-11 pm 11:14:5415 *16 * * * public class JavaBeanDemo1 implementsHttpsessionbindinglistener{23 Private String name;20 @Override22 public void Valuebound (Httpsessionbindingevent event) System.out.println (name+ "was added to the session"),}25 @Override27 public void Valueunbound (httpsessionbinding Event event) {System.out.println (name+ was kicked out by the session);}30 to public String getName () {+ RET Urn name;33}34 public void SetName (String name) {this.name = name;37}38 All public JavaBean Demo1 (String name) {this.name = name;41}42}

JavaBeanDemo1 This JavaBean implements the Httpsessionbindinglistener interface, the JavaBean object can perceive the two operations that are bound to the session and removed from the session. The test code is as follows:

1 <%@ page language= "java" pageencoding= "UTF-8"%> 2 <% @page import= "Me.gacl.domain.JavaBeanDemo1"%> 3 <! DOCTYPE html> 4 

The results of the operation are as follows:

  

2.2. Httpsessionactivationlistener interface

  JavaBean objects that implement the Httpsessionactivationlistener interface can perceive themselves as activated (deserialized) and passivated (serialized) events
When a JavaBean object that is bound to a HttpSession object is about to be passivated (serialized) with the HttpSession object, the Web server calls the JavaBean object's void Sessionwillpassivate ( Httpsessionevent event) method. This allows the JavaBean object to know that it will be serialized (passivated) to the hard disk along with the HttpSession object.
When the JavaBean object that is bound to the HttpSession object is about to be activated (deserialized) with the HttpSession object, the Web server calls the JavaBean object's void Sessiondidactive ( Httpsessionevent event) method. This way the JavaBean object will know that it will be deserialized (activated) back into memory with the HttpSession object

Example:

 1 package me.gacl.domain; 2 3 Import java.io.Serializable; 4 5 Import Javax.servlet.http.HttpSessionActivationListener; 6 Import javax.servlet.http.HttpSessionEvent; 7 8/** 9 * @ClassName: JavaBeanDemo210 * @Description: 11 implements the Httpsessionactivationlistener interface JavaBean object can perceive itself to be activated and blunt Event 12 Activation: The JavaBean object is deserialized (activated) into memory together with the session.     13 passivation: JavaBean object exists in session, when the server serializes the session to the hard disk, if the JavaBean object in the session implements the Serializable interface 14     The server then serializes the JavaBean object in the session to the hard disk, and the JavaBean object and session are serialized to the hard disk as a passivation 15 If the JavaBean object in the session does not implement the Serializable interface, the server will first remove the JavaBean object that does not implement the Serializable interface in the session 16 and then serialize the session (Passivation) To hard disk 17 when the JavaBean object bound to the HttpSession object is about to be passivated with the HttpSession object, the Web server calls the JavaBean object object's void Sessionwillpassivate (Ht Tpsessionevent Event) method 19 Such a JavaBean object will know that it is going to be serialized (passivated) to the hard disk with the HttpSession object 20 when the JavaBean object bound to the HttpSession object is going to be with the Ht After the Tpsession object is activated, the Web server calls the JavaBean object's void Sessiondidactive (Httpsessionevent event) method 22 so that the JavaBean object can know that it is going to HttpSEssion objects are deserialized (activated) back into memory. * @author: Aloof Wolf * @date: 2014-9-11 PM 11:22:3525 *26 */public class JavaBeanDemo2 Implemen TS httpsessionactivationlistener,28 Serializable {for private static final long Serialversionuid = 7 589841135210272124l;32 Private String name;33 @Override35 public void Sessionwillpassivate (Httpsessione     Vent se) {System.out.println (name+) and session are serialized (passivated) to the hard disk, the session ID is: "+se.getsession (). GetId ()); 38 }39 @Override41 public void sessiondidactivate (httpsessionevent se) {System.out.println (name+) and S Ession together from the hard disk deserialization (activation) back to memory, the session ID is: "+se.getsession (). GetId ());}44 public String getName () {Retu RN name;47}48-public void SetName (String name) {this.name = name;51}52, public Javabeand Emo2 (String name) {this.name = name;55}56}

To observe the process of binding to the JavaBean object in the HttpSession object with the HttpSession object being passivated to the hard disk and re-activating back into memory from the hard disk, We need a tomcat server to help us complete the passivation and activation process for HttpSession objects, as follows:

Create a context.xml file under the Webroot\meta-inf folder, as follows:

  

The contents of the Context.xml file are as follows:

1 <context>2     <manager classname= "Org.apache.catalina.session.PersistentManager" maxidleswap= "1" >3     <store classname= "Org.apache.catalina.session.FileStore" directory= "GaCl"/>4     </manager>5 </Context>

The HttpSession object is passivated to a GaCl folder on the local hard disk after 1 minutes of configuration in the Context.xml file file

The JSP test code is as follows:

1 <%@ page language= "java" pageencoding= "UTF-8"%> 2 <% @page import= "Me.gacl.domain.JavaBeanDemo2"%> 3 <! DOCTYPE html> 4 

Access to this JSP page, the server will immediately create a HttpSession object, and then implement the Httpsessionactivationlistener interface JavaBean Object Bound to the Session object, the JSP page after waiting for 1 minutes no one again access, then the server will automatically passivation (serialization) of this HttpSession object to the hard disk,

  

We can find the session serialized to the local store under the Work\catalina\localhost\javaweb_listener_20140908\gacl folder of the Tomcat server, as shown in:

  

When the JSP page is accessed again, the server will automatically reactivate (deserialize) the HttpSession object on the hard disk that has been deactivated (serialized) back into memory. The results of the operation are as follows:

  

Javaweb development technology in the content of the listener technology so much, in peacetime work, listener technology in the Javaweb project development is more used, so must master this technology.

Javaweb Learning Summary (45)--Listener (Listener) Learning Two

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.