Custom Tag Libraries

Custom tag libraries, added to JSP in Version 1.1, enable developers to encapsulate complex functionality inside of HTML-like tags. Basically, you can write your own action tags. If you remember from earlier in this chapter, actions are JSP tags for using implicit objects and other server-side objects, and for defining new scripting variables. They typically take the form of <jsp: action name/>. A Web developer can use these tags from a custom tag library just like any other HTML or JSP tag.

Using Custom Tag Libraries in JSP

Custom tag libraries are designed to hide complexity behind simple JSP tags. The following JSP code (main.jsp) demonstrates just how simple they are to use:

<%@ taglib uri="tlds/stockPrice.tld" prefix="stock" %>

<!doctype html public "-//w3c/dtd HTML 4.0//en">
<HTML>
<BODY>

<H1>Today's Stock Price</H1>

<stock:stockPrice tickerSymbol="PRAS" /> <p>

<stock:stockPrice tickerSymbol="GIRD" />

</BODY>
</HTML>

Figure 4-11 shows this page displayed in a Web browser.

Figure 4-11. Output of a Custom Tag Library


In this case, we've created a page that relies upon a custom tag library to print out the stock price for our fictional company, Prasad Systems, which trades under the symbol PRAS. A second company is shown as well. This is a standard JSP page that includes two special tags. The first is a standard directive that specifies a tag library descriptor (TLD):

<%@ taglib uri="tlds/stockPrice.tld" prefix="stock" %>

This tag specifies that our JSP page uses the TLD file stockPrice.tld. A TLD is an XML file that contains mappings from the tags in the tag library to the handler classes that are also part of the tag library. The developer also creates these handler classes. The preceding directive specifies that the tag library should handle every tag that begins with the prefix "stock". Note that the preceding path is a relative path. You must specify the TLD relative to the WEB-INF directory in your Web applications directory.

Then we insert a tag that calls the appropriate method to return the current stock price of Prasad Systems:

<stock: insert StockPrice tickerSymbol="PRAS" >

This tag outputs some HTML that lists the stock price. It also is possible to create a library that returns objects for use inside of the JSP page. This mechanism is used extensively in the WebAuction application.

Building a Custom Tag Library

There are two steps in creating a custom tag library. First, you build a TLD that specifies what tags in the library match to what handlers. Then, you build the handlers themselves—the Java classes that are executed by the JSP container when the appropriate tags are used in JSP pages.

The TLD

As noted, the TLD is an XML-encoded file that specifies what tags are to be handled by the tag handler classes that you write. This file is named with a .tld extension. The following demonstrates the format for this file:

<? xml version="1.0" ?>   → The version of XML that this is encoded in.

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag
Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">   →
The document type for this XML document.

<taglib> → A tag saying that we are now starting definition of a
tag library

<tlibversion>1.0</tlibversion> → version of the tag libraries
implemented
<jspversion>1.1</jspversion> → version of JSP being used.
<tag>
<name>StockPrice</name>

<tagclass>com.learnweblogic.examples.ch4.StockPriceHandler</tag-
class>

<info>A Comment/Descriptor of the Tag</info>

<attribute>  ß A tag saying that we'll now define an attribute

<name>tickerSymbol</name> → The name of the attribute
      <required>true</required>  → Whether attribute is required
      <rtexprvalue>true</rtexprvalue> →Whether attribute can be
expression

</attribute>

</tag>  → To specify that this tag is finished.

</taglib>

The .tld file is included in the taglib.war example on the CD, in the directory named examplesch4. It is a sample TLD that specifies a tag library with a single tag that inserts a stock price based on the stock symbol provided. This single tag, named StockPrice, is handled by a class called com.learnweblogic.examples.ch4.stockHandler. This handler has one attribute, tickerSymbol. Remember, attributes are values sent as parameters when the tag is used.

The WebLogic Server package includes documentation on every possible field for the TLD. You can find this on the Web at http://e-docs.bea.com/wls/docs60/taglib/tld.html.


When developing a tag library, you probably will not write a TLD from scratch. Either use an integrated development environment such as WebGain Studio or IBM VisualAge, or modify the TLD that is included in this book and in the WebLogic Server samples.

The Tag Library Handler

Basic tag library handlers are simple to implement. There are four basic requirements:

  • Have your class extend the javax.servlet.jsp.tagext. TagSupport class. This class provides implementations of all the methods required by the javax.servlet.jsp. tagext.Tag interface. The basic APIs you need to implement for the JSP container to call your handler are included for your convenience.

  • Create a get<attribute> and set<attribute> method for each tag attribute. These are the methods that the container requires to pass parameters to your handler.

  • Create a constructor and a destructor for your tag handler. The constructor is called by the container to instantiate your handler. The destructor is defined in a method called release() and called at the end of your handler's life in code to release resources.

  • Create methods that do the work and output named doStartTag() and doEndTag(). These methods are called at the beginning and end of the evaluation of your tag, respectively. They are analogous to the service() method in the servlet specification. Each of these returns status codes that tell the JSP container how to evaluate either your custom tag or the entire JSP page.

Tag Library Handler Simplified Lifecycle

The lifecycle for a tag handler is as follows:

1.
WebLogic Server instantiates your tag handler by calling your constructor method when it first appears on the JSP page.

2.
WebLogic Server takes all attributes and values out of the tag and calls the respective set<attribute> method for each that is not already set. When the tag is first used, no attributes are set, so the set method is called for everyone.

3.
WebLogic Server then calls doStartTag() and subsequently calls doEndTag() for your handler.

4.
WebLogic Server continues processing the JSP page. If your custom tag handler is required again, steps 2 through 4 are repeated with the same instance of your handler.

5.
Finally, at the end of the JSP page, the release() method is called to dispose of all the resources that you are using. These might be database connections for example, or variables that you have created.

Tag Library Handler Example (StockPriceHandler.java)

Let's implement a handler for the stock price tag that we specified in the previous two sections. First, import the necessary classes:

package com.learnweblogic.examples.ch4;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.Hashtable;
import java.io.Writer;

Next, define the class. Notice that the class extends

javax.servlet.jsp.tagext.TagSupport:

public class StockPriceHandler extends TagSupport {

And, define a constructor and a destructor for this tag handler:

public StockPriceHandler() {
super();
    }

/* Called when the container wants to dispose
of the current tag library. */
public void release() {
myTickerSymbol = myOptionSymbol = null;
super.release();
    }

Next, define a get<attribute> and set<attribute> method for each attribute:

public void setTickerSymbol (String ts) {
myTickerSymbol=ts;
    }
public String getTickerSymbol () {
return myTickerSymbol;
    }

When a tag handler executes, the JSP container first calls the doStartTag() method, much like the service() method of the servlet:

public int doStartTag() throws JspException {
/*

  You could place any work that you want to have done here.

  This method returns a status code.  There are a number of dif-
ferent options for these codes, which are discussed later in this
section.  This one instructs WebLogic Server not to evaluate any
expressions inside of the body of the tag.

  At this point, you would insert code to go out and get the
stock price from your source.  Take that value and put it into a
string variable named 'price'.
*/

  String stockPrice=price;

  try {

    JspWriter out = pageContext.getOut();
    out.print(myTickerSymbol + ":" + price);

  } catch (Exception e) {
     e.printStackTrace();
     throw new JspException(e.getMessage());
  }

  return(SKIP_BODY);

}


private String myTickerSymbol;
private String price = "25 cents";
}

In this handler, only the start tag method is required because we do not care about evaluating expressions inside of the tag. Otherwise, we would need to implement the end tag method.

All the work gets done within the start tag method. When the method is called, it gets the current output stream, which is the response being prepared for the client requesting the JSP page, and prints out the stock price text into that stream.

Packaging Custom Tag Libraries

If you are packaging a Web application, put your JSP pages and custom tag libraries into the package. First, place your TLD XML files into the META-INF directory in your jar package. Put the JSP files in the appropriate directories in the jar package; then add your compiled tag files into WEB-INF/classes. The previous example would have its compiled classes placed in the package under WEB-INF/classes /com/mypkg. Then, deploy your Web application as stated in the documentation for your application server.

Running the Tag Library Example in WebLogic Server

The tag library example is included on the CD for this book. It is available in the directory examplesch4 aglib.war. To install and run it, use the same steps that you followed for the JavaBean example in the previous sections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.189.220