JSP Custom Tags


As you develop your JSP application, you might find common functionalities that you repeatedly have to code in Java on the JSP page. For example, you might need to present metric values in English units, as in the previous example. JSP enables you to extend the JSP syntax by adding new custom tag libraries to JSP.

There are two pieces to a JSP tag library (taglib). The first is a Java class that actually handles the JSP. The second is a tag library descriptor file (TLD) that lets JSP know about the new tags.

To begin, you need to define a Java class that extends BodyTagSupport . This class provides all the helper functions and default methods needed to implement the BodyTag . Listing 5.13 shows an implementation of a meters -to-feet tag.

Listing 5.13 MetersToFeet.java
 package taglib.metric; import javax.servlet.jsp.tagext.BodyTagSupport; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.PageContext; import javax.servlet.http.HttpServletResponse; import java.text.DecimalFormat; public class MetersToFeet extends BodyTagSupport {     public int doAfterBody() {        BodyContent body = getBodyContent();        try {            float meters = Float.valueOf(body.getString()).floatValue();            DecimalFormat df = new DecimalFormat();            df.setMaximumFractionDigits(precision);            body.getEnclosingWriter().println(df.format(meters * 3.28));        } catch (Exception ex) {            ex.printStackTrace();        }        return EVAL_PAGE;     }     int precision = 2;     public int getPrecision () {        return this.precision;     }     public void setPrecision (int precision) {        this.precision = precision;     } } 

As you can see, all this class does is to define one bean property called precision , and overrides the doAfterBody() method provided by the base class.

The doAfterBody() method is called after the body inside the custom tag is encountered . In this case, all it does is to covert the String into a float , format it to the specified number of decimal places (two if no argument is given in the tag), get a handle on the stream to write to, and send out the converted number.

After the class is written, you must inform JSP that the new tag is available. This is done via a TLD file. The TLD for the metric taglib is shown in Listing 5.14.

Listing 5.14 metric.tld
 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"           "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>metric</shortname> <tag> <name>m2f</name> <tagclass>taglib.metric.MetersToFeet</tagclass> <bodycontent>JSP</bodycontent> <attribute>    <name>precision</name>    <required>false</required> </attribute> </tag> </taglib> 

This simple TLD defines the metric taglib, which has a single tag called m2f (meters to feet). m2f is mapped to the class you just created and defined to have one attribute: the precision. Just as in a set property, any attributes of a tag are mapped to the accessor methods of the class.

With the TLD file placed in the WEB-INF subdirectory of your application, you can write a JSP file that uses it (see Listing 5.15).

Listing 5.15 tagtest.jsp
 <%@ taglib uri="/WEB-INF/metric.tld" prefix="metric" %> <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> <title>Testing Metric Tags</title> </head> <body> <h1>Testing Metric Tags</h1> 30 meters is <metric:m2f>30</metric:m2f> feet<BR> 37.98345 meters is about <metric:m2f precision="4">37.98345</metric:m2f>feet<BR> </body> </html> 

After loading the new taglib using the <%@ taglib directive, you can use the new tag by simply putting <metric:m2f in your JSP. This example shows versions using both a specific precision and the default. Figure 5.3 shows the results.

Figure 5.3. Pointing your browser at tagtest.jsp .

graphics/05fig03.gif



Struts Kick Start
Struts Kick Start
ISBN: 0672324725
EAN: 2147483647
Year: 2002
Pages: 177

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