Section 15.1. Getting Started with Custom Tags

   

15.1 Getting Started with Custom Tags

Tag libraries are fairly complex. In ColdFusion, it is very easy to start writing CFML custom tags. It isn't in JSP. That is, unless you know a little Java. Then you realize that all that is happening is that you're extending a certain set of classes and then describing the tag in an XML format. With everything we now know about Java you should find it much easier to get started writing custom tags than would a Web developer with little or no Java knowledge. This accounts somewhat for the structure of this book. Custom tags are simply much more important in JSP than they are in ColdFusion. That's because ColdFusion already has 90 tags for you to work with right out of the box. JSP doesn't. So in this section we will see how to write custom tags.

15.1.1 Beans and Tags

There are distinct differences between writing a custom tag and a bean, though they share certain goals. We will look briefly at these so that you can wisely choose when to write a tag and when to write a bean.

First of all, it is generally easier to write and deploy a bean than a tag. All you have to do is define your class and call <jsp:useBean/> . This may come down to who is on your development team, what their roles are, and what the life of the application will be like. For example, if you work in a job shop and plan on reusing your e-commerce application for a number of different clients , then using tags is a great choice because of the simplicity and familiarity they afford designers.

A major difference is that tags can manipulate content and beans cannot. You can define tags devoted to HTML output or formatting, for instance.

Beans can add flexibility within an application. That's because they can be defined in one servlet or JSP and then used in a different one. Custom tags, on the other hand, can add flexibility across multiple applications. Their work assignments often make them self-contained. Because of the different kinds of work beans and tags are often assigned, it can be easier to port tag libraries. Developers often make their tag libraries available for free download or for sale; one doesn't generally see "bean libraries."

15.1.2 Custom Tag Syntax

The syntax of a custom tag is exactly like the syntax of the predefined JSP actions. It consists of a prefix, followed by the name of the tag. The prefix is the name of the tag library you define.

 <prefix:tagname /> 

In practice this syntax looks like this:

 <jsp:include page="some.jsp"/> 

When you write custom tags, they follow the same form:

 <ecommerce:cart action="addItem" itemID="5" /> 

Here we reference a tag called cart in the ecommerce tag library. It has two attributes, action , which defines what specific thing we want to do in the cart, and itemID , which specifies the product to work with in the tag.

15.1.3 Defining Custom Tags

There are a few things necessary to make custom tags work. It is not like in ColdFusion where you can write a file with a certain name and then reference it directly without having to even restart your server.

Note

JRun 4 now has "hot deployment"; Tomcat, however, requires that you restart it every time you make any change to Java classes. The basic rule is this: If you modify only the code, such as scriptlet code, in a JSP, then you can simply restart the page to see your change; if you modify a bean, a custom tag class, or any regular Java helper class, you need to restart Tomcat for the change to take effect.


To begin with, you need a tag library. These are all of the classes that make up the Java program the custom tags call. The second thing you need is the taglib directive. You write this into your JSP to signify that you will be using this library; the directive also specifies the prefix name you will use to reference your library. Third, you need a tag library descriptor, or TLD. This is an XML document that describes the library. In the following sections, we'll discuss these in more detail. Finally, we need to tell Tomcat's web.xml file (or other corresponding file in a different container) that we will use this tag library.

15.1.4 Tag Handlers

The tag handler is responsible for evaluating tag actions during execution of the calling JSP. Every tag library must support one of the tag handler classes, which allow passing information between the tag and the caller. These handlers are javax.servlet.jsp. tagext .TagSupport and javax.servlet.jsp. tagext.BodyTagSupport . These utility classes provide the basic built-in functionality to make custom tags work. As their names imply, these classes serve a different kind of tag writing. If you want to make a tag that does not need to evaluate any body content (anything between the opening and closing tags), then you can extend javax.servlet.jsp.tagext.TagSupport . Tags in different languages that do not need to evaluate any body content include the following:

 <br>  <cfset name="value> <jsp:forward page="some.jsp"/> <cart:view /> 

Note

The API reference included with this book contains the complete listing of javax.servlet.jsp classes and their methods and constants. It is a good idea to read over this so that you know what functionality is built into the API.


Note

Because they are XML-compliant, regular JSP tags and custom tags must include a trailing slash if they do not have a separate closing tag.


The TagSupport class has a number of methods that are useful. These include the following:

  • doStartTag() defines processing for the beginning tag. It corresponds to ThisTag.ExecutionMode = "start" in ColdFusion.

  • doEndTag() performs the work designated in the closing tag. It corresponds to ThisTag.ExecutionMode = "end" in ColdFusion.

  • release() releases tag state.

  • setPageContext(PageContext pageContext) returns void , setting the pageContext for the current JSP.

  • getParent() returns the parent tag.

Note

Remember, custom tags and all things JSP and servlet are not part of the J2SE ”they are in the J2EE, and so you won't find information about their classes or methods in the API we've been using for most of this book. This API is currently available at http://java.sun.com/j2ee/sdk_1.3/techdocs/api/.


The doStartTag() method is executed as soon as the tag is instantiated . The doEndTag() is executed the moment doStartTag() completes. These methods both return int values in the guise of readable text messages (Java constants) such as SKIP_BODY or EVAL_BODY . The container decides what action it needs to take next based on the value returned.

Here are the int values that doStartTag() returns:

  • EVAL_BODY_INCLUDE indicates that the body between the opening and closing tags should be included in the output stream. A tag returning this value must extend TagSupport and cannot process the body content (though it can be included in the output stream).

  • EVAL_BODY_TAG indicates that a new BodyContent object should be created and the body of the tag should be processed . Only tags extending BodyTagSupport can return this value.

  • SKIP_BODY indicates that a body should not be processed if one exists.

The doEndTag() method can return either of the two following values:

  • EVAL_PAGE indicates that the container should continue processing the remainder of the JSP.

  • SKIP_PAGE indicates that the container should not continue processing the remainder of the JSP.

15.1.5 The taglib Directive

The taglib directive ties the JSP page to the TLD and sets the namespace prefix for the tag to use on the page. Its job is to import the tag library to make it available for use on this JSP.

It looks like this:

 <%@taglib uri="/WEB-INF/tlds/myTaglib.tld"            prefix="ecommerce" %> 

Call this at the top of your JSP to make your tag library available. The uri must reference a custom XML-based description of the tags in the library called a TLD. The prefix is what you use as a prefix to reference the tag on the JSP caller.

15.1.6 The Tag Library Descriptor

The Tag Library Descriptor (TLD) serves two purposes. First, it contains all of the information required by the runtime to know what to execute during JSP translation. Second, it contains information to assist JSP authoring tools in understanding and displaying this information.

When the JSP is translated into a servlet at runtime, the TLD for each of the libraries associated with the page is loaded. Next, the TLD is parsed and the information contained in it is offloaded to helper classes. Then it waits. When the runtime encounters a reference to a tag in the JSP, it visits the data stored in the helper classes and validates the tag's syntax. Finally, it creates a stub for the tag (which is why you see a stubs directory in CFMX).

An example of a TLD follows . We'll use an expanded version of this listing in the next chapter.

15.1.7 example.tld

 <?xml version="1.0" encoding="ISO-8859-1" ?>  <!DOCTYPE taglib PUBLIC     "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"     "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib>     <tlib-version>1.0</tlib-version>     <jsp-version>1.2</jsp-version>     <short-name>ecommerce shopping cart libary</short-name>     <description>a shopping cart</description>     <tag>         <name>message</name>         <tag-class>com.javaforcf.store.tags.MessageTest         </tag-class>         <body-content>empty</body-content>         <description>test: show a message</description>         <attribute>             <name>message</name>             <required>true</required>             <rtexprvalue>false</rtexprvalue>             <type>java.lang.String</type>         </attribute>     </tag> </taglib> 

In the above TLD, a number of things happen. First, we declare that this is an XML document and declare its namespace.

Note

The TLD must be syntactically valid. If it is not, your custom tag will not work, and Tomcat will tell you the problem on startup. That means that you must take care of typical XML things, such as making sure that the XML declaration begins at the very first column of the document.


Then we write a top-level <taglib> element, specifying the version of the library and the version of JSP used. The short name and description tags are arbitrary strings describing the tag library. Next, each tag in the library must have its own <tag> element. In the above example, only one tag is declared; more would be annexed in just this way. Any attributes must be declared, and you must specify whether or not they are required.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net