The JSP Files (part 8): Tagged And Bagged

Learn how to speed up JSP code development with custom tag libraries.

The Beginning Of The End

Over the past few weeks, we've taken you on a guided tour of the intricacies of JSP, beginning with basics like conditional statements and loops, and quickly moving on to more complex things like form processing, session management, and error handling.

But all good things must come to an end - and so, in this final episode of The JSP Files, we'll be briefly touching on a few other facets of this powerful server-side scripting language.

Playing Tag

One of the most exciting features about JSP is the ability to build and use custom "tag libraries" in your JSP applications. A "tag library" is a reusable block of JSP code, typically written to replace Java code with easy-to-read-and-understand tags (similar in appearance to HTML markup). Once written, these tag libraries can be used over and over again, thereby bringing a new element of reusability to the language.

In addition to reusability, tag libraries also offer substantial advantages from the maintenance point of view. Since tag libraries are largely defined using XML-type markup, they make it possible to separate application presentation from application logic - which, in turn, implies that designers and developers working on Web applications can use a tag without worrying about how and why it works. This separation between program code and final layout is something most designers would kill to have - and it's now available to almost anyone who knows how to string together Java and JSP code.

Another advantage of the separation discussed above, is the ease of use when it comes to adding new features to a tag library, or making changes to existing features. Since a tag library is portable and reusable, a change made to it will immediately reflect in all JSP pages using that tag library. Similarly, a new feature added to the tag library becomes immediately available to all pages carrying that library.

Tag libraries are slowly catching on, with many JSP developers releasing custom tag libraries for free online. These libraries are typically designed for specific tasks - database connectivity, string manipulation and the like - and they provide a rich vein for JSP developers to mine for their own projects. After all, why waste time writing Java code to send email messages when you can find a feature-rich, properly-tested and free tag library to do the same thing online?

Looking Inside

A tag library is made up of several components. First comes the tag class itself, written in Java - this contains all the behind-the-scenes code which makes the tag function. This class will be referenced in the tag library descriptor, and constitutes the meat of the sandwich we're building.

Next, you need a "tag library descriptor", an XML file usually identified with the .TLD file extension. This TLD contains information on different aspects of the tag library: the name of the tag, and of the Java class associated with it, a short description of functionality, and optional attributes and body content.

Both these components are usually packaged into a JAR file for easy distribution.

Now, we're not going to get into the nitty-gritty of writing a tag library here - there are already a whole bunch of tutorials which discuss this in detail, and links to some are included at the end of this article. What we will do, however, is illustrate how a tag library can be incorporated into your JSP document, and how it interacts with the rest of your script.

In order to illustrate this, we'll be using the Jakarta Project's DATETIME tag library, designed to manipulate date- and time-stamps. You can download a copy of this library from http://jakarta.apache.org/taglibs/doc/datetime-doc/intro.html, and you can find a number of other freeware tag libraries at http://www.jsptags.com/, one of the larger repositories on the Web.

Once you've downloaded a copy of the library, you need to tell Tomcat about it before you can begin using it. The first step here is to decide the context within which you plan to use the library - for purposes of this example, we will assume the context is "/test/". Next, copy the TLD file from the distribution into the context's "web-inf/" directory, and the main JAR file into the context's "web-inf/lib/" directory.

The last step here is to open up the "web.xml" file which resides in the "web-inf/" directory, and alter it to reflect the new tag library - this is accomplished via the <taglib> directive.

<taglib> <taglib-uri>http://jakarta.apache.org/taglibs/datetime-1.0 <taglib-location>/WEB-INF/datetime.tld

This element specifies the location of the tag library, as well as a unique URI used to reference it.

Meeting Popeye

At this point, you can begin using the new tag library in your JSP pages. First, declare it with the "taglib" directive - this directive must appear before any custom tags in the page.

<%@ taglib uri="http://jakarta.apache.org/taglibs/datetime-1.0" prefix="popeye" %>

The URI is the unique identifier for the tag library, and must match the URI specified in "web.xml", while the prefix appears in every call to a custom tag, and is used to distinguish between tags from different libraries in the same page.

Once the library has been declared, you can begin using custom tags in your JSP scripts. Consider the following example, which uses a custom tag from the DATETIME library to calculate the number of seconds elapsed since January 1 1970.

<html>
<head>
</head>
<body>

<%@ taglib uri="http://jakarta.apache.org/taglibs/datetime-1.0" prefix="popeye" %>

The number of milliseconds since January 1, 1970 is <popeye:currenttime/>

</body>
</html>

And the output is:

The number of milliseconds since January 1, 1970 is 987165837280

What if you simply want the current date and time? By combining the <currenttime> tag with the <format> tag, the DATETIME library makes it a snap!

<html>
<head>
</head>
<body>

<%@ taglib uri="http://jakarta.apache.org/taglibs/datetime-1.0" prefix="popeye" %>

The current date and time is
<popeye:format pattern="hh:mm EEE MMMM dd yyyy">
<popeye:currenttime/>
</popeye:format>

</body>
</html>

In case you're wondering, the EEEs and MMMs you see there are formatting codes, used to define the format in which the date and time is to be printed. Here's the output:

The current date and time is  06:22 Fri April 13 2001

The example above also illustrates how some tags can be nested within one another - this can make for powerful combinations, and is one of the clever things about this architecture.

How about generating a list of days or months? The DATETIME library's got you covered with its <weekdays> and <months> tags...

<html>
<head>
</head>
<body>

<%@ taglib uri="http://jakarta.apache.org/taglibs/datetime-1.0" prefix="popeye" %>

<form>
Select a day
<select name="weekday">
<popeye:weekdays id="day">
<option value="<jsp:getProperty name="day" property="dayOfWeek"/>">
<jsp:getProperty name="day" property="weekday"/>
</popeye:weekdays>
</select>
</form>

</body>
</html>

The DATETIME library comes with a whole bunch of other useful tags too - take a look at the documentation to see the various other features available.

You've Got Mail!

Now, our original thesis was that tag libraries would allow Web designers with no knowledge of JSP to implement complex functionality on a Web page. While the examples you've just seen were simple and illustrative, they haven't really proved that thesis - after all, it's reasonable to suppose that any competent Web designer would know how to manipulate date and time values via JavaScript and wouldn't really require a tag library for the purpose. So let's try something most client-side specialists wouldn't know how to handle - email delivery.

Typically, the process of generating email from a Web site is handled via a server-side script - Perl gurus open a pipe to sendmail, while PHP programmers reach for the mail() function. This implies a foreknowledge of either PHP or Perl - not something a novice Web designer may be expected to possess. What solution does JSP offer this poor soul?

The Jakarta MAILER library.

Using a couple of simple tags from this library, any Web developer can quickly add mail-processing capability to a Web page - in fact, the process is simpler than the equivalent techniques in Perl and PHP. Take a look.

<html>
<head>
</head>
<body>

<%@ taglib uri="jspmailer" prefix="jmail" %>

<jmail:mail server="mail.server.com" to="recipient@server.com" from="sender@server.com" subject="This stuff is pretty cool!">
<jmail:message>
OK, you've convinced me - this tag library thing is awesome! Where do I sign up?
</jmail:message>
<jmail:send/>
</jmail:mail>

</body>
</html>

By simplifying otherwise complex code, custom tag libraries like the one above can promote both efficiency and harmony in group development projects, by allowing the developers to concentrate on building better tools (libraries) and the designers to concentrate on presentation (rather than code). As JSP evolves, you can expect tag libraries to grow in importance - even now, they are by far one of the most compelling reasons to choose this server-side language over others.

Applet Antics

You've already seen how JSP "actions" work - in the last article, for example, we demonstrated the <jsp:useBean> and <jsp:setProperty> actions in conjunction with JavaBeans, while <jsp:include> was illustrated in the very first article in this series. However, we missed out on a couple of important ones - and so, we'd like to introduce you to <jsp:plugin>, used to incorporate Java applets into a Web page.

The <jsp:plugin> directive takes care of generating all the HTML code necessary to embed and activate a Java applet. Consider the following example:

<html>
<head>
</head>
<body>

<jsp:plugin type="applet" code="NewsTicker.class" name="newsticker" height="100" width="100">

<jsp:params>
<jsp:param name="x" value="10"/>
<jsp:param name="y" value="25"/>
<jsp:param name="cx" value="90"/>
<jsp:param name="cy" value="114"/>
<jsp:param name="bgcolor" value="102,102,153"/>
<jsp:param name="textcolor" value="0,0,0"/>
<jsp:param name="hilitecolor" value="255,0,0"/>
</jsp:params>

<jsp:fallback>Oops! Something bad happened and I can't display this applet</jsp:fallback>

</jsp:plugin>

</body>
</html>

The code above sets up the applet contained in "NewsTicker.class", and passes it a bunch of name-value pairs of parameters. The <jsp:param> tag is used to pass these parameters to the applet, while the <jsp:fallback> directive contains error text, in the event that the applet cannot be found or displayed.

When JSP compiles and renders the page, the code above is automatically converted to its HTML equivalent.

<html>
<head>
</head>
<body>

<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="100"  height="100"  codebase="http://java.sun.com/products/plugin/1.2.2/jinstall-1_2_2-win.cab#Version=1,2,2,0">
<PARAM name="java_code" value="NewsTicker.class">
<PARAM name="type" value="application/x-java-applet;">
<PARAM name="cy" value="114">
<PARAM name="cx" value="90">
<PARAM name="bgcolor" value="102,102,153">
<PARAM name="hilitecolor" value="255,0,0">
<PARAM name="y" value="25">
<PARAM name="x" value="10">
<PARAM name="textcolor" value="0,0,0">
<COMMENT>
<EMBED type="application/x-java-applet;"  width="100"  height="100" pluginspage="http://java.sun.com/products/plugin/" java_code="NewsTicker.class"
cy=114
cx=90
bgcolor=102,102,153
hilitecolor=255,0,0
y=25
x=10
textcolor=0,0,0
>
<NOEMBED>
</COMMENT>
Oops! Something bad happened and I can't display this applet
</NOEMBED></EMBED>
</OBJECT>

</body>
</html>

And finally, the <jsp:forward> directive is used to automatically redirect a client request to another document. The following code would automatically redirect the client to the script "endzone.jsp".

<jsp:forward page="endzone.jsp" />

Just as in the previous example, additional parameters can be passed to the new script via <jsp:param>. For example,

<jsp:forward page="endzone.jsp">
    <jsp:param name="user" value="joe" />
    <jsp:param name="uid" value="653" />
    <jsp:param name="gid" value="1220" />
</jsp:forward>

And with that, it's about time to call this a wrap. We hope you enjoyed it, and that it served as a good starting point for your entry into the world of JSP.

If you're interested in learning more about the topics discussed in this series, take a look at Sun Microsystems' JSP pages at http://java.sun.com/products/jsp/, Java documentation and references at http://java.sun.com/docs/, or the tutorial on tag libraries at http://java.sun.com/products/jsp/tutorial/TagLibrariesTOC.html. If, on the other hand, you have questions, comments, or large sums of money for us, drop us a line - we'd love to hear from you!

Until next time...stay healthy!

Note: All examples in this article have been tested on Linux/i586 with Tomcat 3.2 and JServ 1.1. Examples are illustrative only, and are not meant for a production environment. YMMV!

This article was first published on08 May 2001.