[ Team LiB ] 10.5 Events So far,
[ Team LiB ] 10.5 Events So far, beans have been fairly self-contained. When a property is obtained or changed or when an instance is saved or loaded, the only objects that know about it are the object that performed the action and the bean itself. Often, it is desirable for beans to communicate with one another. For example, a JSP might have a bean that is used as a shopping cart and another bean that handles inventory. When a product is placed in the cart, the inventory bean should be told that one less item of this product is available for other shoppers. The JSP could handle this manually, by calling the appropriate methods on both beans. Besides being inconvenient, this would risk potential problems with programmers forgetting to call the right methods in the right order. Instead, beans support numerous mechanisms to communicate directly with one another. Beans were originally designed as graphic components, such as buttons or menus. In this role, a bean would be driven by events, such as a user clicking a button. Other beans would need to listen for a set of events and react appropriately. This leads to an event-based communication mechanism being incorporated into the bean specification, and this mechanism turns out to be useful for server-side programs as well. The shopping cart might generate, or fire, an event when an item is put into it, and the inventory bean might listen for this event and react by decrementing its supply. Event programming is almost as easy as property programming and once again is expressed mostly as a set of naming conventions. First, it is necessary to define a class to represent the event. Listing 10.5 shows an event that represents putting an item in a shopping cart. Listing 10.5 An event package com.awl.jspblog.ch10; public class PurchaseEvent extends java.util.EventObject { private String itemName; public PurchaseEvent(Object source,String itemName) { super(source); this.itemName = itemName; } public String getItemName() {return itemName;} } Once the event has been defined, it is necessary to define an interface that will listen for events of that type, such as the one in Listing 10.6. Listeners are defined as interfaces, which allows any class to declare that it will listen for any set of events. Listing 10.6 A listener interface package com.awl.jspblog.ch10; public interface PurchaseListener extends java.util.EventListener{ public void purchaseMade(PurchaseEvent e); } This interface has only one method, but it is allowable for a listener interface to have an Page 190
Note: If you are looking for good and affordable webspace to host and run your servlet application check Sandzak servlet hosting services