4.4.3 bound attributes
The bound Property indicates that when the value of this property changes, the propertychange event is automatically triggered to notify other objects that the property has changed. The event encapsulates the attribute name, the original value of the attribute, and the new value after the attribute changes.
The following example shows how to use the bound attribute: Write A Javabean to receive the name variable. When the value of the name variable changes, the changes are displayed on the page.
First, create a JavaBean class named bound. java. The file code is shown in code 4-9.
Code 4-9 bound. Java
Package com; Import java. Beans .*; Public class bound { Private string name; /* Send information to the listener object */ Private propertychangesupport support = new propertychangesupport (this ); Public bound (){ } /* Bind the event listener object to the bound object and add it to the listener queue */ Public void addpropertychangelistener (propertychangelistener listener ){ If (Support = NULL ){ Support = new propertychangesupport (this ); } Support. addpropertychangelistener (listener ); } /* Remove the listener object from the listener queue */ Public void removepropertychangelistener (propertychangelistener listener ){ If (Support = NULL ){ Support = new propertychangesupport (this ); } Support. removepropertychangelistener (listener ); } Public void setname (string name ){ String TMP = Name; This. Name = Name; /* Events that notify the listener of changing the property value of the current object of all events in the listener queue */ Support. firepropertychange ("name", TMP, name ); } Public String getname (){ Return name; } } |
The listener is a listen. Java class, and the file code is shown in code 4-10.
Code 4-10 listen. Java
package com; import java.beans.*; public class Listen implements PropertyChangeListener{ private String inform; Public listen (){ INFORM = "the attribute value in bean has not changed "; } /* Events triggered after the property value changes */ Public void propertychange (propertychangeevent EVT ){ INFORM = "the attribute value in bean has changed "; } Public String getinform (){ Return inform; } }
|
The page showing property changes is listen. jsp. The file code is shown in code 4-11.
Code 4-11 listen. jsp
<% @ Page contenttype = "text/html; charset = GBK" %> <% @ Page import = "com. Bound" %> <% @ Page import = "com. Listen" %> <HTML> <Head> <Title> bound test </title> <Head> <Body> <% Bound = new bound (); Listen listen = new listen (); Bound. setname ("James "); %> <P> <B> name = <% = bound. getname () %> </B> <% Bound. addpropertychangelistener (Listen ); Bound. setname ("Li Si "); %> <HR> <% = listen. getinform () %> <HR> <B> name = <% = bound. getname () %> </B> </Body> </Html> |
The running result of the attribute change page is 4-7.
|
(Click to view the larger image) Figure 4-7 attribute change display page |