300 9.4.1 CHAPTER 9 Posing conditions with tags

Summary author or content developer from concerns over conditional logic so they may focus on presentation. A solution that bases itself on beans should look something like: ” property=”myQuery”> < %-- We are here if the query is true --%> < %--We are here if the query is false --%> This approach keeps the JSP syntax clean and straightforward, while enforcing a tidy separation of the business logic and presentation. The advantages of using Java- Beans to evaluate your conditions make it vastly superior to the previous approach, while satisfying all the requirements of supporting complex, real-world use. 9.5 Summary While it is feasible to implement an easy-to-use conditional tag, representing a condition (even a simple one) in a declarative manner is impossible. Therefore, unless you are going to implement your own condition specification language, you will be better off implementing your condition evaluation in a JavaBean, in which you can leverage all the power of the Java language to pre-process and evaluate your conditions. This approach leaves your tags with the sole task of checking the JavaBean s resulting values and including or excluding content based on the bean s exported values. Once you resolve to never attempt implementing a full-fledged condition specification language, implementing custom conditional tags becomes relatively easy. JSP is well adapted for conditional inclusion (as well as exclusion) of content using the Tag method call protocol and JSP will evaluate the conditioned content with no additional effort on your part. In the next chapter, we will look at how to build tags that support iteration, such as iterating over a list of JavaBean property values. We saw scriptlet code in chapter 8 that performed iteration; now we ll see how to eliminate these scriptlets and replace them with simple to use, flexible custom tags that perform the same functions.

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

300 9.4.1 CHAPTER 9 Posing conditions with tags

300 9.4.1 CHAPTER 9 Posing conditions with tags Supporting complex conditions with a condition language Inventing a condition language is a reasonable approach to supporting conditions; in fact, we had a very simple type of condition language in our TestTag. Why not improve on it? For example, assume that our condition can look like this: Some JSP code … One resounding benefit to creating a new condition language is that you can make it as complex and as powerful as you desire. Since you ll have total control over the language, you can support as many operands, functions, or comparisons as you desire by extending it. At this level, defining our own conditional language seems like a good approach. There are, however, several notable drawbacks. Drawbacks of complex condition languages By designing your own condition language you can easily support complicated queries; however, to do so you need first to develop a complex parsing mechanism and then implement all the functionality the language supports, including utility functions (such as Trim() in the previous example). This can prove to be a substantial undertaking. Furthermore, once you are finished with new language implementation, you will have to teach it to whomever will be using it. And if that were not enough, you will probably need to provide mechanisms for JSP authors to debug their conditions. Will you provide an IDE to let developers step into your proprietary implementation? After this analysis, it becomes clear that in order to build a debuggable, feature-rich condition language (and the code to support it) you end up building a system similar to commercial products like ColdFusion. Unless you are planning on selling this tag library commercially and for a nifty price, the effort required to support complex conditions this way is not worth it. There must be a better way to solve the problem with a more standard condition language and less effort. One alternative, it turns out, is to use Java. Supporting complex conditions with JavaBeans JSP already supports Java. To take advantage of this, let s place all our conditions in a JavaBean and query the values of that bean s properties. The JavaBean now contains the complicated Java code that performs the condition, and can leverage all the natural features of the Java language. This approach also makes it very easy to debug the code (since you can simply use your favorite Java IDE), and prevents us from supporting any complex parsing or training JSP authors in our own proprietary language. Though this method requires you to write the beans that contain the conditional logic, this will simply be handled by the business logic developer, freeing the JSP

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

CHAPTER 9 Posing conditions with tags in testing

Improving our advanced condition tags B Points to the User-Agent header. C Informs the wrapper tag that we are going to allow the execution of multiple successful tests By setting the multichoice attribute to true, we indicate that all tests wrapped in this WithTag should be evaluated. For example, if you try to access this JSP fragment from Internet Explorer running on Win98, both the MSIE and 98 containment conditions will come up true and you will see the body of these tests in the response. If you wonder why someone would want to have several successful tests in the same JSP fragment, just picture some JSP code in which you want to adapt yourself to the browser as much as possible. In this case you will need to test the browser s capabilities over and over again. Using the multichoice option can give you this flexibility. D Execution of an if-else logic first test if the header contains MSIE and then check that it does not. E Provides an Integer as a second operand. F Checks if the User-Agent header does not start with a Mozilla/ prefix (most browsers do). Note from these two samples that using our tags is fairly straightforward; the tag attributes make sense and we ve kept the syntax to a minimum. It is also easy, using this library, to test the reference object and specify conditions; but aren t these conditions too elementary for many real-world uses? The next section will discuss this concern. 9.4 Improving our advanced condition tags The tags we ve built do a fair job of handling condition evaluation, so what s missing? The main shortcoming with our tag library is that many real applications have conditions that use more than two operands, which is the maximum our library can handle. In Java we can have conditions that look like: if(s.trim().equals( somevalue ) && someBoolean && otherBoolean) { // do something } Such a condition could not be represented using our current library. Does it mean that we cannot use condition tags in a real-world case? There are a number of possible ways to support these complex conditions within tags. Here are two of them: Invent a complex condition language to be used within the tags and extend the tags we developed to use this language. Have the user of the tags put all of the complex conditions inside a bean and use the bean s attributes to grab the condition s result inside the tags.

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

CHAPTER 9 Posing conditions with tags in testing

CHAPTER 9 Posing conditions with tags in testing a boolean value; the conditions we use are eq true and eq false, meaning equals true and equals false. We are not doing a simple if-else (we actually can t), but instead are asking about two negatives. Listing 9.8 Using the conditional tags with a boolean value < % Boolean b = new Boolean(true); %> TRUE FALSE You may wonder about the fact that in listing 9.8 we generated our object in a scriptlet (about the easiest way to pass a value to the tag), but don t let it concern you. We could get this value from anywhere in the JSP environment (e.g., we could get this value from a bean) and our tag would work equally well. Another sample JSP fragment shows a more complex scenario in which the developer grabs the User-Agent header and checks to see what type of client is being served. Listing 9.9 A complex usage of the conditional tags d Yes No
e You are probably using some Windows98 variation.
f What’s that? No Mozilla?

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

CHAPTER 9 Posing conditions with tags is needed

The advanced condition tag family false scope false false index false true property false false test book.conditions.TestTag book.conditions.TestTagExtraInfo JSP Pose a condition on the reference object. condition true false As seen in the TLD, both tags are marked as having JSP contents, which tells the JSP environment to evaluate the body. As for tag attributes, the WithTag entry inherits most of its attributes from ReflectionTag and adds just a single new multichoice attribute, instructing the tag as to the condition evaluation policy that is desired. TestTag, on the other hand, is less complex with only a single tag attribute that specifies the condition string. 9.3.4 Our tag library in action We can now take a look at a few JSP fragments that use the tag. You ll recognize the following JSP fragment from earlier in this chapter; and it will prove even more useful based on what we ve just learned. This fragment shows how the tag is employed

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

CHAPTER 9 Posing conditions with tags is needed

CHAPTER 9 Posing conditions with tags is needed to validate the binary operator is to search the look-up table for a valid operator. Happily, this means that a developer will not need to change TestTagExtraInfo in order to add new operators. 9.3.3 TLD for the advanced condition tags To complete our discussion of advanced condition tags, we shall also provide the important tag library descriptor, as well as sample JSP code that take advantage of the condition tags. First, let s look at the tag library descriptor as presented in listing 9.7. Listing 9.7 Tag library descriptor for the advanced condition tags < ?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 simp http://www.manning.com/jsptagsbook/condition-taglib Condition tags library. with book.conditions.WithTag book.conditions.WithTagExtraInfo JSP Wrap a JSP fragment with test conditions. multichoice false false object false true name false

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

CHAPTER 9 Posing conditions with tags i If

The advanced condition tag family much. The answer to these concerns is in listing 9.6 where you see the implementation of TestTagExtraInfo. Listing 9.6 Source code for the TestTagExtraInfo class package book.conditions; import javax.servlet.jsp.tagext.TagData; import javax.servlet.jsp.tagext.TagExtraInfo; import book.util.StringUtil; public class TestTagExtraInfo extends TagExtraInfo { public boolean isValid(TagData data) { String condition = data.getAttributeString(“condition”); String[] parsed = StringUtil.splitArray(condition, ” “); if((parsed[0].equals(TestTag.OPER_EXISTS) || b parsed[0].equals(TestTag.OPER_NEXISTS)) && parsed.length == 1) { return true; } if(parsed.length == 2 && null != TestTag.operators.get(parsed[0])) { c return true; } return false; } } B Checking the unary operators for correctness, we need to individually check each operator name. C Checking the binary operators for correctness, all we need is a single look-up in the operator table. TestTagExtraInfo provides one more reason for using an operator table instead of hard-coding the operators in TestTag; just look at the difference between the validation of the unary and binary conditions. Since the implementation of the unary operators is hard-coded in TestTag, TestTagExtraInfo must create an if statement with the specific unary operator, which will force a developer that adds another unary operator to modify both as well as TestTag. On the other hand, since the binary operators are implemented with an operator look-up table, all that

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

CHAPTER 9 Posing conditions with tags i If

CHAPTER 9 Posing conditions with tags i If the condition is true, notify the policy logic in the wrapping tag using setSelected(). J The implementation of the unary operators is hard-coded in the tag. 1) Gets the operator object from the operator table. The name of the operator saves as the key. 1! Evaluates the condition operand. Two metachars may prefix the operand value, a # signs for an integer value, a $ informs us that the following string is a JSP scripting attribute name The condition may have a single operand or two. In both cases the first operand is the one held within the wrapping WithTag; the second, however, comes from the condition string. The condition string describes the condition using a syntax we ve developed (recall, this string was eq true or eq false in listing 9.2). In general, the binary condition string looks like: , in which the condition operator can be one of the operator names held within the operator tables and the condition operand is the second operand to be used within the condition. We wanted the second operand to be as flexible as possible, but without adding too much of a burden to the JSP developer. The solution was to add some special metacharacters to the operand in the following way: If the operand starts with a #, then following the # is an integer value, and the second operand should be an Integer object that was created from this value. If the operand starts with a $, then following the $ is the name of a JSP scripting variable (some Java object) whose value should be used as the second operand. If the operand does not start with $ or # it is a plain string value. These three rules make the second operand very flexible, yet keep things simple for the JSP developer. 1@ All our binary operators implement the same Operator interface. This way we can handle many different operators the same way. In a nutshell TestTag s job is to evaluate its condition and, based on the result, to embed (or not) its body content in the response. This is accomplished relatively simply because of the work partition between WithTag and TestTag. TestTagExtraInfo We saw that TestTag created a framework where we can plug additional operators as needed. With all these operators, you might expect the TagExtraInfo associated with TestTag to be huge. Will we have to change it whenever we add a new operator? If so, this entire flexible operator framework does not seem to be worth all that

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

CHAPTER 9 Posing conditions with tags protected boolean

The advanced condition tag family static class ContainsOperator implements Operator { boolean reference; public ContainsOperator(boolean reference) { this.reference = reference; } public boolean cmp(Object lh, Object rh) { return ((lh.toString().indexOf(rh.toString()) != -1) ? reference : !reference); } } static class EqualsOperator implements Operator { boolean reference; public EqualsOperator(boolean reference) { this.reference = reference; } public boolean cmp(Object lh, Object rh) { return (lh.toString().equals(rh.toString()) ? reference : !reference); } } // Other operators were removed for clarity … } B j1)1@Prepares a lookup table with condition operator names as keys and the operator implementation as value TestTag shows (on purpose) two methods to implement multiple condition operators. The unary operators (comparing only one operand) are hard-coded inside TestTag, while the binary operators (comparing two operands) are implemented by a set of classes (each implementing a different operator) and a Hashtable, used as a look-up table for the correct operator. Looking into the two methods, it is obvious that the second is much cleaner and can scale well (i.e., adding many more operators should not pose a problem). By implementing each operator in a different class, it is much easier to extend TestTag to handle new operators. One can modify TestTag to read a resource file with the operator names and implementing classes and avoid the coupling between the tag and its operators. C TestTag has a single attribute which is the condition to test. D If the condition is true, include the body in the response, otherwise ignore it. E Get a reference to the wrapper tag and keep it for later use. F Consult the condition policy logic in the wrapper tag before evaluationg the condition. If we are not allowed to run, this is just like a false condition. G Single operand, send to the unary condition evaluator. H Two operands, send to the binary condition evaluator.

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