Java reflection Once we have a Class object

CHAPTER 8 Using JavaBeans with tags All parameters and return codes in invoke() are passed wrapped within an object type. If some of the parameters or the return value are of primitive types (such as char) they need to be wrapped in an object (such as java.lang.Character). Table 8.3 presents the primitive types and their corresponding wrapping objects. The object on which invoke() will execute the method is passed as the obj parameter to invoke(). Since the number of parameters differs from one method to another, invoke() accepts an array of objects in which we place the parameters according to the order of declaration. The value returned from the invoked method is returned from invoke() (wrapped in an object if necessary). Exceptions thrown by the invoked methods are thrown by invoke() wrapped inside a java.lang.reflect.InvocationTargetException (from which you can then obtain the original exception). All methods that return type information, for example getParameter- Types(), return Class objects that represent this type. Even void has a Class object of type java.lang.Void to represent it. Table 8.3 The primitive types and their corresponding wrappers Primitive type Wrapper class boolean java.lang.Boolean char java.lang.Character byte java.lang.Byte short java.lang.Short int java.lang.Integer long java.lang.Long float java.lang.Float double java.lang.Double The Method class provides the functionality we need to call any method with whatever arguments are necessary for a given class. This class will be very useful as we build our JavaBean tags.

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

Java reflection Once we have a Class object

Java reflection Once we have a Class object for our class, we may use methods such as getConstructors(), getMethods(), and getFields() to retrieve information about this class. The Method class For the purpose of this book, the class most important to us is Method, mainly because, by obtaining a Method object from a certain class, we are able to call that method repeatedly and on any instance of this class. This is the approach we will use to call the get and set property methods within the custom JavaBean tags we are building. The methods that are part of the Method class are presented in table 8.2, along with a brief description of each. Table 8.2 Methods in the Method class Method name Description getDeclaringClass() Returns a Class object that represents the class or interface to which that method belongs. Think of it as the Class object that, if you call one of its getMethod() methods, will return this as the Method object. getModifiers() Returns an integer representation of Java language modifiers. Later on, the Modifier utility class can decode this integer. getName() Returns the name of the method. getParameterTypes() Returns an array of Class objects that represent the parameter types, in declaration order, of the method. getReturnType() Returns a Class object that represents the return type of the method. invoke(Object obj, Object[] args) Invokes the underlying method on the specified object with the specified parameters. getExceptionTypes() Returns an array of Class objects representing the types of exceptions declared to be thrown by the method. equals(Object obj) Compares this Method against the specified object. hashCode() Returns a hashcode for this Method. toString() Returns a string describing this Method. Some of the methods mentioned in table 8.2, such as equals(), hashCode(), and toString() do not require any real explanation, as anyone familiar with Java programming knows how and when to use these methods. The remainder of the methods, however, require some ground rules:

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

Java reflection discussing the integration of reflection, JavaBeans,

CHAPTER 8 Using JavaBeans with tags By now you have seen how reflection is used to learn about a class at runtime. The tags we build in this chapter, like the standard JavaBean tags, will take as tag attributes the reference to an instance of a JavaBean and, for our printing tag, also the name of the property to print. Since the JSP author may specify any JavaBean instance at all, our tags will need to be able to take that instance at runtime and use reflection to find and call the proper methods. It should be clear that the only way to accomplish this is through the reflection API. Let us look at the syntax of that API in greater detail. NOTE Using the reflection API in order to introspect methods and later invoke them follows strict security rules that disallow overriding the Java security model. For example, one may not introspect private and package protected classes. 8.1.2 The reflection API The reflection APIs are contained in the Java package java.lang.reflect. Some of the more important classes in this package are shown in table 8.1. Table 8.1 Classes that are important for reflection Class Description Class Represents a Java class. Although not part of the java.lang.reflect package, this class is very important for reflection. Method Represents a method of class (also allows that method to be called). Array Supports creation and accessing of Java arrays (without having to know the exact type of the array in advance). Constructor Represents a specific class constructor (and allows that constructor to be called). The Class class The means to obtain all the constructors, methods, and fields for a particular class (or interface) in Java is through an instance of java.lang.Class. We obtain an instance of Class that corresponds to a particular Java class in a couple of ways: Calling Class.forName( com.manning.SomeClass ) where com.manning. SomeClass is the fully qualified name of the class we want to study. Referring to the class field of a particular Java class. Code for this looks like: Class c= com.manning.SomeClass.class

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

Java reflection discussing the integration of reflection, JavaBeans,

Java reflection discussing the integration of reflection, JavaBeans, and custom tags, a quick look at the Java reflection API is in order. This will not be an in-depth description of reflection or method invocation by using reflection, but will provide a helpful explanation of the technology, its advantages, and the API that can put it to good use. 8.1.1 What is reflection? Javasoft describes the purpose of the reflection API as to enable Java code to discover information about the fields, methods, and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. Quite a mouthful, so what does all that mean? In brief, the reflection API lets us learn about a particular Java class and then use that knowledge to properly call methods, get and set fields, or call the constructor of any instance of that class. The reflection API is particularly useful for debuggers and development tools that need to browse classes and display certain information from the classes to the user. The API is also useful when parts of your Java program have to interact with any type of Java object and need to learn about it at runtime. The tags we create in this chapter will have this requirement, since they will be designed to work with any and all JavaBeans. This definition can be clarified with a few examples of programs that use Java reflection. Reflection and development tools Consider the case of an environment wherein a developer manipulates program components through the GUI of a Java IDE (like JBuilder, Visual Caf , etc.). We recognize that the development environment knows nothing about the components in advance, yet it must be able to present the developer with the possible methods that can be used in each component. Spying on the component to discern the interfaces, methods, and properties they expose can be accomplished using the reflection API, and is better known as Introspection. Reflection and scripting engines Another case is one wherein a user employs a JavaBean-capable scripting engine to create an application. Since a script is not usually precompiled with all its components, it does not know anything in advance about the different JavaBeans components with which it will interact at runtime (not even their type); yet, during runtime it should be able to perform the following: Introspect the components to find the method that it should execute. Dynamically execute the method on the scripted object. Both of these functions are available through the reflection API.

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

8 Using JavaBeans with tags In this chapter

CHAPTER 8 Using JavaBeans with tags One of the most common tasks in any Java program is to get and set properties of JavaBeans. Web development in Java is no different in that respect. In an object-oriented Java web application, your servlets and JSPs likely contain a good deal of code that interacts with JavaBeans. For servlets, working with JavaBeans is the same as is in any other Java program: beans are instantiated and the proper get or set methods are called. JSPs interact with JavaBeans differently, by using three standard tags that are defined in the JSP specification (, , and ). These tags, discussed in chapter 2, instantiate beans, introduce them to the page as scripting variables, and set properties in the beans in addition to printing properties back to the user. Unfortunately, the functionality exposed by the JavaBeans-related tags is rather limited. Two of the more troublesome limitations are: The tags cannot operate on objects unless they were introduced to the page via a JavaBeans-related JSP tag. The tags cannot manipulate indexed properties (properties that have multiple values and are referred to by an index like getSomeProperty(i)). These shortcomings render JavaBeans standard tags useless for solving many practical problems such as iterating over an indexed property of a bean, or printing an attribute value of a bean that we would rather not introduce as a JSP scripting variable. Not surprisingly, developers increasingly find themselves in need of a more versatile set of JavaBeans tags. In this chapter, we address that need. To this end we ll create a custom tag library that supports interaction with Java- Beans, free from the limitations of today s standard tags. We start with a brief discussion of the Java reflection API, which we ll soon see is crucial to building our JavaBean tags. We then move on to discuss the JavaBean component standard and how reflection assists us in getting and setting properties of Java Beans. We finish by creating our custom tag library which will consist of two tags: one that allows us to expose any JavaBean as a JSP scripting variable, and one that supports printing of the value of any JavaBean property to the user. 8.1 Java reflection If tags are to be useful, they must be created such that they are versatile enough to get and set the properties of any JavaBean. This requires that they be capable of calling a bean s get or set methods, simply by knowing the class name of the Java- Bean and the name of the property to be manipulated. If you ve heard of the Java reflection API, you know that it is a set of Java methods and classes that allows us to do just that. Using reflection, we can learn about the attributes of any Java class (including its methods) and even call any method of the class we choose. Before

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

Summary type=”email”/> b Asserting a single parameter based

CHAPTER 7 Building a tag library for sending email We also covered how assertions can be implemented. All applications need to check their input parameters, and normally this requires a fair amount of Java code. Yet, as we saw, a great deal of what is needed for parameter checking can be accomplished declaratively, using tags similar to the assertions developed for our tiny application. The key issue here is not that we can cover 100 percent of possible validations, but that we can extend our assertions whenever there is a need and that the code within the assertions can now be reused without any modification. Ultimately, the goal of this chapter was to apply the previously discussed concepts of tag development to a library with real-world use. A gradual approach was chosen to enforce not only the mechanics of tag development, but also to understand fully the tools at our disposal for producing a well-designed, robust solution.

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

Summary type=”email”/> b Asserting a single parameter based

Summary type=”email”/> < %-- snip Starting with this point we are back to the previous JSP file snip --%> b Asserting a single parameter based on its type, the existence assertion is implicit. Asserting on a named parameter became a very simple matter. We actually reduced many potential scriptlets (to validate parameters) and made our page more robust. Our AssertTag may not be the Holy Grail (we cannot pose really complex questions on the parameters) but it is extensible. However, even with the relatively limited functionality that we have, assertions can solve most problems we confront in our daily work. 7.6 Summary Tags have clearly facilitated sending emails with dynamically generated content from within a JSP. We have gone from something that usually requires in-depth know-how, such as SMTP and Java mail, and rendered its power in such a pervasive way that any page author comfortable with tags can use it. The key issue was not the underlying email technology, but how to create a simple, robust interface to that technology with custom tags. The role of custom tags is not to develop a new technology, but to enable rapid development and to expose a wanted technology in the most convenient, pervasive way to your JSP developers. Is there a drawback to the tag approach? Perhaps. A Java developer may look at the tags and believe that they are less easy to use than JavaBeans. He or she may say, Hey, I put all that effort into the tag and all I got is functionality that I could have implemented with a couple of scriptlets and a simple email bean . This may be true, yet that effort freed us from the need to maintain all the scriptlets involved in JavaBeans usage, and helped further separate the duties of Java coders from the JSP page authors.

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

Adding assertions and input validation B Gets a

CHAPTER 7 Building a tag library for sending email exists false false oneof false false Listing 7.20 shows how all the attributes in AssertTag are constant strings. Why did we exclude runtime expressions for this tag? Because translation time validation of runtime attributes is impossible, and incorrectly configured assertions may cause problems ranging from plain embarrassment (this site is throwing exceptions instead of showing a reasonable error page) to profit loss (if the assertion needs to rule out stolen credit card numbers). By preventing assertions from being runtime expressions, we discover any syntax problems in our attributes before the page is requested by a user (at translation time), and well before any damage can occur. It is preferable to be safe than sorry, so we ve decided that the assertion tag is one such case. Using assertion mail tags in the registration JSP file Having developed the assertions, let s use them in our registration page (listing 7.21). In its current sample state, the registration page accepts three parameters: The user s email Validate with an existence and type (email) assertions. The user s name Validate with an existence and type (alpha) assertions. The user s family name Validate with an existence and type (alpha) assertions. An error in any one of the three parameters ought to trigger an internal redirection to an error handler that will present the offending parameter. Listing 7.21 A JSP file employing the assertion email tags < %@ taglib uri="http://www.manning.com/jsptagsbook/email-taglib" prefix="mail" %> < %@ taglib uri="http://www.manning.com/jsptagsbook/assert-taglib" prefix="assert" %> JSP Web Hosting services

Adding assertions and input validation B Gets a

Adding assertions and input validation B Gets a condition value and validates it using the appropriate assertion object Note how easy it is to implement AssertExtraInfo. All of the actual validation work is performed by isValidCondition(), so that all AssertExtraInfo needs to do is fetch the condition values from TagData and use the appropriate assertion object to validate it. Creating the TLD The last item to discuss before using AssertTag is its TLD entry (listing 7.20). Listing 7.20 Tag library descriptor for AssertTag < ?xml version="1.0" encoding="ISO-8859-1" ?> < !DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd> 1.0 1.1 assert http://www.manning.com/jsptagsbook/assert-taglib A tag library for the assert tag assert book.assert.AssertTag book.assert.AssertExtraInfo empty Asserts based on a set of conditions parameter true false handler true false type false false

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