The Show tag name of the request object

CHAPTER 8 Using JavaBeans with tags sample JSP file presents different usage patterns for the tag. Sometimes it is employed in an elementary way. For example, we only specify the JSP attribute name associated with the object (optionally the scope) and the name of the property. There might be a case, however, in which the tag is used with runtime expressions and indexed properties; in fact, we produce a fine table with the header names and values by using the tag with the header indexed property. This section showed how easy it is to print the values of JavaBeans properties back to the response flowing to the user. Now we move on to build the second tag of our library, which allows us to export new JavaBeans from our tags and have them serve as scripting variables in the page. 8.4 Exporting bean values from tags Exporting new scripting variables from a tag is a handy feature. For example, a JDBC connection tag can connect to a database and export a JDBC connection as a scripting variable so that JSP scriptlets further down the page may use the connection object. Though useful, exporting a new scripting variable is more than a minor maneuver for the JSP engine; it first needs to know: The Java type of the new scripting variable so that a correct Java scripting variable will be declared for the newly exported object. The duration (scope) of the scripting variable. Sometimes you want your Java scripting variable to last until the end of the page; in other cases you may want it to exist within the body of the tag. The JSP environment needs to be informed of that. The name of the scripting variable. This reflective information must arrive at the JSP environment in order to take advantage of it while translating the JSP file to a servlet. The methods to provide this information were defined in the JSP specification, which we will present now. Next, we take a look at a tag whose job it is to export JavaBean property values as new JSP scripting variables. 8.4.1 Informing the runtime of exported scripting variables The JSP specifications define a simple way to inform the JSP runtime of the exported scripting variables, by overriding yet another method in TagExtraInfo. Up until now, the only method we overrode in TagExtraInfo was isValid(), which we used to validate tag attribute syntax and values. The TagExtraInfo class also allows you to indicate any scripting variables your tag will export by overriding getVariableInfo().

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

The Show tag name of the request object

The Show tag name of the request object –%>

< % Enumeration e = request.getHeaderNames(); c while(e.hasMoreElements()) { String name = (String)e.nextElement(); %>

Header Value
< %= name %> B Shows the request locale. C Creates a table of header names and values. Starts by enumerating the header names. D Prints the header value We are using runtime expression to define the object we work with and to provide the index into the header property. E Gets the value of the response s committed property It should be false, since writing back to the user has not started. Throughout the entire JSP file we never defined any of the objects used as a Java- Bean; ShowTag will treat any object we give it as a bean, and this lets us take the regular request and response objects and use them without prior definition. This

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

The Show tag String name = data.getAttributeString(“name”); String

CHAPTER 8 Using JavaBeans with tags book.reflection.ShowTag book.reflection.ReflectionTagExtraInfo empty Show a certain object property value. object false true name false false scope false false index false true property false false ShowTag in action We can create a JSP file that uses our new tag to show bean properties; the JSP driver (listing 8.8) uses our tag to explore the values present in the request and response objects (this is possible since both objects are JavaBeans). Listing 8.8 JSP file that uses ShowTag < %@ page import="java.util.*" %> < %@ page errorPage="error.jsp" %> < %@ taglib uri="http://www.manning.com/jsptagsbook/beans-taglib" prefix="bean" %> < %--javax.servlet.jsp.jspRequest is the JSP attribute Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

The Show tag String name = data.getAttributeString(“name”); String

The Show tag String name = data.getAttributeString(“name”); String scope = data.getAttributeString(“scope”); if(o != null) { c if(null != name || null != scope) { return false; } } else { if(null == name) { d return false; } if(null != scope && e !scope.equals(ReflectionTag.PAGE_ID) && !scope.equals(ReflectionTag.REQUEST_ID) && !scope.equals(ReflectionTag.SESSION_ID) && !scope.equals(ReflectionTag.APPLICATION_ID)) { return false; } } if((null != data.getAttribute(“index”)) && f (null == data.getAttribute(“property”))) { return false; } return true; } } B The object attribute must be the product of a runtime expression. C If the object was provided through a runtime expression, the name and scope attributes should not be used. D If the object is not provided through a runtime expression, we must provide a variable name. E The scope value must be one of the four defined scopes. F We cannot provide an attribute index without specifying a property. ShowTag s TLD All that is left for us to do before using ShowTag in a JSP file is to create a TLD (listing 8.7). Note in this listing that not all the attributes are mandatory. This loss of control is required by the flexible functionality that was required from the tag. Listing 8.7 Tag library descriptor entry for ShowTag show

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

The Show tag BPoints to the object whose

CHAPTER 8 Using JavaBeans with tags Listing 8.5 Source code for the ShowTag handler class package book.reflection; import book.util.LocalStrings; import javax.servlet.jsp.JspException; public class ShowTag extends ReflectionTag { static LocalStrings ls = LocalStrings.getLocalStrings(ShowTag.class); protected void processObject(Object v) b throws JspException { try { writeHtml(pageContext.getOut(), v.toString()); } catch(java.io.IOException ioe) { // User probably disconnected … // Log and throw an exception } } } B Overrides processObject() to print the property value. TagExraInfo for ShowTag The last portion of code left unseen is the TagExtraInfo that we shall attach to the ShowTag. In fact, since ShowTag does not add any new attribute or syntactic constraints, we can actually take a TagExtraInfo, as developed for ReflectionTag, and use it for ShowTag (listing 8.6). Listing 8.6 Source code for the ReflectionTagExtraInfo class package book.reflection; import javax.servlet.jsp.tagext.TagData; import javax.servlet.jsp.tagext.TagExtraInfo; import javax.servlet.jsp.tagext.VariableInfo; public class ReflectionTagExtraInfo extends TagExtraInfo { public boolean isValid(TagData data) { Object o = data.getAttribute(“object”); if((o != null) && (o != TagData.REQUEST_TIME_VALUE)) { b return false; }

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

The Show tag BPoints to the object whose

The Show tag BPoints to the object whose property we want to get We can have either the object itself or its name and scope (optional). There are two ways to specify the object used by the tag: one way is to set the object as a runtime expression value, the other is to specify the name and the scope. These two object specification methods are mutually exclusive, and our TagExtraInfo implementation should take care of this. But we are getting ahead of ourselves. CgRefers to the property name and the index (optional) in this property The property value is specified by two attributes: the property name and an index into the property. The index is not mandatory and the tag can handle cases in which the index is not specified. The index, you ll recall, may be a string or an integer; but how can we specify two different types using a single attribute? We cheat! We specify the integer within a string, but prefix its value with a # so that the tag knows that the value represents an integer. Why are we giving an advantage to the string? Because strings are far more useful as an index when we are creating web pages. In most cases, we will index our properties using a string, as it was felt that string indexing should be easily done. DdoStartTag() fetches the property value and lets the tag process it using process- Object(). EFetches the object If the object was configured as a runtime value, either use it, or get a reference to it using the name and the scope. FAs soon as we receive the object, fetches the property value. GA # prefix denotes an integer Translates the string to an integer. HGets the propery value using the beans utility class. IprocessObject() is a method that an extending class can overide to process the value of our object property As previously stated, ReflectionTag is an abstract class whose job is to provide access through reflection to properties in the JSP scripting objects. In this spirit, we defined an empty method named process- Object() that can be overridden by an extending class, whose only goal is to manipulate the property value. Implementing processObject() is not mandatory and, for many cases, it may be better to override doStartTag() and use the method getPointed() directly; however, for the purpose of our new ShowTag (listing 8.5), overriding processObject() is enough. ShowTag The ShowTag handler is the handler for the tag to be used by the JSP author, and inherits from ReflectionTag to make use of its introspection work. This tag then retrieves the value for a property and prints it to the user.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

The Show tag public void setProperty(String property) {

CHAPTER 8 Using JavaBeans with tags return PageContext.REQUEST_SCOPE; } else if(scope.equalsIgnoreCase(SESSION_ID)) { return PageContext.SESSION_SCOPE; } else if(scope.equalsIgnoreCase(APPLICATION_ID)) { return PageContext.APPLICATION_SCOPE; } // Log and throw a JspTagException } protected Object getPointedProperty(Object v) throws JspException { try { Object indexParam = null; if(null != index) { if(index.startsWith(“#”)) { g indexParam = new Integer(index.substring(1)); } else { indexParam = index; } } return BeanUtil.getObjectPropertyValue(v, h property, indexParam); } catch(InvocationTargetException ite) { // Log and throw a JspTagException } catch(IllegalAccessException iae) { // Log and throw a JspTagException } catch(IntrospectionException ie) { // Log and throw a JspTagException } catch(NoSuchMethodException nme) { // Log and throw a JspTagException } } protected void processObject(Object v) i throws JspException { } protected void clearProperties() { obj = null; objName = null; objScope = null; property = null; index = null; super.clearProperties(); } }

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services

The Show tag public void setProperty(String property) {

The Show tag public void setProperty(String property) { this.property = property; } public void setIndex(String index) { this.index = index; } public int doStartTag() throws JspException { processObject(getPointed()); d return SKIP_BODY; } protected Object getPointed() throws JspException { Object value = (null == obj ? e getPointedObject(objName, objScope) : obj); if(null != property) { value = getPointedProperty(value); f } return value; } protected Object getPointedObject(String name, String scope) throws JspException { Object rc = null; if(null != scope) { rc = pageContext.getAttribute(name, translateScope(scope)); } else { rc = pageContext.findAttribute(name); } if(null == rc) { // Log and throw a JspTagException } return rc; } protected int translateScope(String scope) throws JspException { if(scope.equalsIgnoreCase(PAGE_ID)) { return PageContext.PAGE_SCOPE; } else if(scope.equalsIgnoreCase(REQUEST_ID)) {

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services

The Show tag interesting; we already know how

CHAPTER 8 Using JavaBeans with tags matching our property name and parameter types. If we find such a method, we assume that it is the one we seek. 1) Places the newly introspected method in the cache. ReflectionTag The class presented in listing 8.3 had nothing to do with tags (in fact, you can use it in any program that employs JavaBeans). The next class, ReflectionTag, is an abstract tag handler that integrates the JavaBeans reflection capabilities to the tag s world: Listing 8.4 Source code for the ReflectionTag base class package book.reflection; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import book.util.LocalStrings; import book.util.ExTagSupport; import book.util.BeanUtil; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.JspException; public abstract class ReflectionTag extends ExTagSupport { public static final String PAGE_ID = “page”; public static final String REQUEST_ID = “request”; public static final String SESSION_ID = “session”; public static final String APPLICATION_ID = “application”; static LocalStrings ls = LocalStrings.getLocalStrings(ReflectionTag.class); protected Object obj = null; b protected String objName = null; protected String objScope = null; protected String property = null; c protected String index = null; public void setObject(Object o) { this.obj = o; } public void setName(String name) { this.objName = name; } public void setScope(String scope) { this.objScope = scope; }

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

The Show tag interesting; we already know how

The Show tag interesting; we already know how a method is called using reflection and the only new issue here is that you see how to provide parameters to the invoked method using an array of objects. E 1) Looks for the method in the introspected methods cache The second method presents several new ideas, starting with the use of a method cache, continuing with introspecting indexed properties, and ending with our own low-level introspection when the default Introspector fails us. The method cache was added when we found out how time-consuming introspection is. In fact, in pages loaded with reflection, adding the method cache gave the pages a 33% performance boost. It s important to remember that the key to the cache needs to be a combination of the object s class, property name, and method parameters. This is a rather complex key, so a new method key object was created (when caching methods for indexed setters, the key is even more involved). If we fail to find a method in the cache, we will introspect it and, when complete, place it in the cache. F Method not in the cache, start introspecting. G Skip methods that do not match our needs H Validate that this method matches our indexed property I Skip methods that do not match our needs Introspecting the class is different from introspection code in listing 8.2, mainly because we now introspect indexed properties. We iterate over the properties descriptor array and differentiate between indexed (instances of IndexedPropertyDescriptor) from non-indexed properties, and then check on the indexed property method. The check includes testing the parameter list of the indexed property, because a certain method in Java may be overloaded. For example, think of the following class: class SuperHero{ Power getSuperPower(int i); Power getSuperPower(String s); } We may want to inspect getSuperPower(String), yet the Introspector will prob ably give us the descriptor of getSuperPower(int). We will then need to skip this descriptor and hope our luck is better elsewhere. J Method was not found using the default introspector; try our own low-level introspection We are finally finished with the property introspection, yet we may not have found the property method. The above example, wherein a specific method has two index types, is a good example of such a case (no, it is not a bug in the default Introspector, just our desire to attain more than the simple indexes regulated in JavaBeans). To overcome cases in which the default Introspector fails to find the needed method, we employ elementary low-level reflection to look for a method

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services