Page 191
Monday, January 29th, 2007Page 191
Note: If you are looking for good and affordable webspace to host and run your servlet application check Sandzak servlet hosting services
Page 191
Note: If you are looking for good and affordable webspace to host and run your servlet application check Sandzak servlet hosting services
[ 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
[ Team LiB ] Page 189
Hint: If you are looking for very good and affordable webspace to host and run your j2ee hosting application check Sandzak.com j2ee web hosting services
[ Team LiB ] 10.4 Bean Serialization As discussed in Chapter 3, one of the remarkable features of beans is their ability to store an instance of a bean, perhaps containing some local configuration data, in a file. As mentioned, this requires no special code in the bean; the class must simply implement the java.io.Serializable interface. Listing 10.4 shows a bean with a main method that allows instances to be created, saved, and loaded. Listing 10.4 A bean that uses serialization package com.awl.jspblog.ch10; import java.io.*; import java.util.*; import java.text.*; public class SaveableBean implements Serializable { private Date createTime; private String message; public SaveableBean() { setDate(new Date()); } public void setDate(Date createTime) { this.createTime = createTime; } public Date getDate() {return createTime;} public void setMessage(String message) { this.message = message; } public String getMessage() {return message;} public static void main(String argv[]) throws Exception { if (argv[0].equals(”-create”)) { SaveableBean sb = new SaveableBean(); sb.setMessage(argv[2]); ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(argv[1])); out.writeObject(sb); out.close(); System.out.println(”Bean created and saved!”); } else if (argv[0].equals(”-load”)) { ObjectInputStream in = new ObjectInputStream( new FileInputStream(argv[1])); SaveableBean sb = (SaveableBean) in.readObject(); in.close(); SimpleDateFormat sdf = new SimpleDateFormat(”hh:mm:ss dd/MM/yy”); Page 188
Note: If you are looking for inexpensive but high quality provider to host and run your serlvet application check Astra servlet hosting services
[ Team LiB ] 10.3 How Beans Work All the JSP/bean functionality is built on the ability of one Java class to discover and invoke methods on another class at runtime. The mechanism that supports this, introspection, has been built into Java since version 1.1. This extremely powerful capability is missing from many other object-oriented languages, in which everything must be known in advance; once a program is built, it may have to be changed significantly to extend it with new functionality. Introspection is possible because a lot of information about method names and signatures is stored in .class files, and certain methods can access and organize this information. An easy way to see the kinds of information that introspection provides is to use the javap utility, which is included in the JDK (Java Development Kit). Javap is run from the command line and is invoked with the name of a class. If it is given SimpleBean from Listing 10.1, Javap will generate the following output: Compiled from SimpleBean.javapublic synchronized class SimpleBean extends java.lang.Object /* ACC_SUPER bit set */ { public int getAge(); public void setAge(int); public java.lang.String getName(); public void setName(java.lang.String); public SimpleBean(); } Although javap does not use introspection to generate this output, the principle is the same. The utility is able to pull out the names of all the methods and the type of their arguments and to return values. From this, a person or a program could infer that there is a property called name that is a string, and so on. Introspection also provides a mechanism to create a new instance of an object once its class has been loaded. This mechanism will construct this instance by looking for a constructor that takes no arguments, which is why the programmer must provide one. As a convenience, if a class contains no constructors at all, Java will automatically provide one that takes no arguments and doesn’t do anything. However, it is always better to make such things explicit. The classes related to introspection are all in the java.beans and java.lang. reflectpackages, and the whole process starts with the java.beans. Introspector class. The use of these classes is beyond the scope of this blog, but readers are encouraged to peruse the JDK documentation to see how all this is accomplished. [ Team LiB ] Page 187
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check professional servlet hosting services
[ Team LiB ] 10.2 Automatic Type Conversion Bean properties can be any type; yet for the most part, JSPs deal with strings. This is certainly true of form parameters, which are the entities that are most often passed to beans’ set methods. If a bean’s set method is expecting an integer and is passed a String, a runtime exception will occur. In most common cases, this potential problem is transparently resolved by the jsp:setProperty and c:set tags, which will try to convert the string to an appropriate type. If the method is expecting an integer, the JSP system will call Integer.parseInt() to obtain an integer value. If this conversion fails, perhaps because the user has entered a string that cannot be turned into an integer, the set method will simply not be called. This can be a problem if some later code expects that all the parameters have been set successfully. There are a few ways to handle this. The first and most obvious is for all set methods to accept strings and do the conversion themselves. However, a more elegant approach would be to use a controller to mediate between the form and the bean. This will be done in Chapter 12. [ Team LiB ] Page 186
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check professional servlet hosting services
[ Team LiB ] Page 185
Hint: If you are looking for very good and affordable webspace to host and run your java hosting application check Sandzak.com java web hosting provider
Page 184
Quick Hint: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services
[ Team LiB ] 10.1 How Beans Are Implemented Internally, a bean is an instance of a Java class, although in common terminology, the class itself may also be referred to as a bean. The most basic kind of bean exposes a number of properties by following a few simple rules regarding method names. In general, a bean provides two methods for each property: a method to get the property and one to set the property, corresponding directly to the jsp:getProperty and jsp:setProperty tags. Together, these methods are known as accessors. Listing 10.1 shows a very simple bean with two properties. Listing 10.1 A simple bean package com.awl.jspblog.ch10; public class SimpleBean { private int age; private String name; public int getAge() {return age;} public void setAge(int age) {this.age = age;} public String getName() {return name;} public void setName(String name) {this.name = name;} } This bean could be used in a JSP just like any other that has appeared throughout this blog:
Hint: If you are looking for good and high quality web space to host and run your java application check Vision java web hosting services
[ Team LiB ] Chapter 10. Writing Beans Chapter 9 provided a bridge between the world of JSPs and the world of Java. We can now cross that bridge to explore those most important of Java classes: beans! This chapter describes beans from a programmer’s perspective and shows how to create beans and make their properties available to JSPs. [ Team LiB ] Page 182
Note: If you are looking for inexpensive but high quality provider to host and run your serlvet application check Astra servlet hosting services