Archive for the 'jsp' Category

[ Team LiB ] 10.7 Bean Errors The

Tuesday, January 30th, 2007

[ Team LiB ] 10.7 Bean Errors The most common problem when using a bean within a JSP is that introspection tends to mask programmer exceptions, making it difficult to see where the problem really is. If a set method throws an exception, the JSP engine will likely print out something cryptic: java.lang.reflect.InvocationTargetException at com.sun.jsp.runtime.JspRuntimeLibrary.introspecthelper at com.sun.jsp.runtime.JspRuntimeLibrary.introspect … etc … The easiest way to discover the real problem is to put the bodies of all the set and getmethods in try/catch blocks and have the catch clause dump the exception to System.err. Although this will cause useful debugging information to be generated, it will leave the bean in an inconsistent state. There is no hard-and-fast rule about what to do in such a situation. The set method could leave the property in its last known state, or it could be reset to a sensible default. Another possibility is to throw the original exception. The user will get an error page, but this might be preferable to getting weird results. Perhaps in a future version of the JSP specification, the JSP engine will listen for VetoEvents, in which case a method could fire such an event on receiving an exception. Another potential problem concerns serialized instances. Consider what would happen if a class contained a member of type int, a serialized instance of this class were created, and then the programmer rewrote the class to make the member a String. Even if the deserialization process were able to build something from this, the result would likely not be meaningful. To prevent this problem, all classes and serialized instances have an ID called the serialVersionUID. When an object is deserialized, the ID of the instance is checked against that of the class; if they do not match, an exception will be thrown. The output from the JSP engine in that case would look something like this: java.io.InvalidClassException: SaveableBean; Local class not compatible: stream classdesc serialVersionUID=8221280906864288240 local class serialVersionUID=-8806858158408665433 If a field has changed types, not much can be done about an error like this, and the only option is to recreate all the serialized instances with the new class. However, some changes are more benign. For example, adding a new field or method should not affect the ability to load old data, as long as it is OK to leave the new fields in an uninitialized state after loading. In most classes, the serial version (UID) value is not implicit but rather is computed based on properties of the class. When the class structure changes, so will this value. However, if old serialized instances should still work with a new class, an explicit form of the ID can be provided to make sure the IDs match. In the preceding case, it would be necessary simply to tell the class to use the same ID as the stream found, which could be done by adding the following line to the class: private static final longserialVersionUID=8221280906864288240L; If an ID has changed because new members were added to the class, the new version of the bean could be given a readObject() method to initialize the new fields after loading. [ Team LiB ] Page 195

Hint: If you are looking for very good and affordable webspace to host and run your tomcat hosting application check Sandzak.com tomcat web hosting provider

[ Team LiB ] Page 194

Monday, January 29th, 2007

[ Team LiB ] Page 194
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra j2ee hosting services

[ Team LiB ] 10.6 Special Events In

Monday, January 29th, 2007

[ Team LiB ] 10.6 Special Events In the bean sense, special events refer to a couple of event types that are of particular interest to bean authors working with JSPs. The first is called PropertyChange Event. A bean may fire one of these any time one of its properties changes, in order to alert other beans to the change. A property that generates a PropertyChangeEvent when it is modified is called a bound property. A bean can also refuse to set a property to a new value, by generating a VetoEvent. This is typically thrown when another object tries to set a property to an unacceptable value. The inventory bean might throw this exception if someone tried to change the number of items it is holding to 1. A property that can generate a VetoEvent is known as a constrained property. These two events are defined in the bean specification. The JSP specification defines an additional event, HttpSessionBindingEvent, which can be used to notify a bean that it has been added to or removed from a session scope. Recall that a session will end after a user has not come back to the site after a certain length of time. When this happens, the session will be deleted to make room in memory for other sessions, and any data in the session will be lost. However, before the session is killed, all data objects connected to it will be sent an HttpSessionBindingEvent, which gives these data objects a chance to save data to a database or file or to do any other cleanup. Listing 10.9 shows a bean that saves itself when the session shuts down. Listing 10.9 A bean that listens for session binding events package com.awl.jspblog.ch10; import java.io.*; import java.util.*; import javax.servlet.http.*; public class SessionBean implements Serializable, HttpSessionBindingListener { private String fileName; private String message; public void setFileName(String fileName) { this.fileName = fileName; } public String getFileName() {return fileName;} public void setMessage(String message) { this.message = message; } public String getMessage() {return message;} public void valueBound(HttpSessionBindingEvent b) { } public void valueUnbound(HttpSessionBindingEvent b) { save(); } Page 193

Hint: This post is supported by Gama web hosting php mysql provider

[ Team LiB ] Page 192

Monday, January 29th, 2007

[ Team LiB ] Page 192
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check professional tomcat hosting services

Page 191

Monday, January 29th, 2007

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,

Monday, January 29th, 2007

[ 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

Sunday, January 28th, 2007

[ 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

Sunday, January 28th, 2007

[ 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

Sunday, January 28th, 2007

[ 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

Saturday, January 27th, 2007

[ 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