HOME  |    TRAINING  |   FREE TUTORIALS   |   JOBS
Find out more about our new RSS feed.
FREE Tutorial
JAVA SERVER PROGRAMMING TAG EXTENSIONS PART 1 - INTRODUCTION

CATEGORY
SEARCH OUR OTHER TUTORIALS

DESCRIPTION

From the point of view of the JSP developer, the only significant new feature of JSP 1.1 is support for tag extensions (often referred to as custom tags). However, this proves to be very significant indeed.
Click here to be kept informed of our new Tutorials.


This free tutorial is a sample from the book Professional Java Server Programming J2EE Edition.


Tag extensions look like HTML (or rather, XML) tags embedded in a JSP page. They have a special meaning to a JSP engine at translation time, and enable application functionality to be invoked without the need to write Java code in JSP scriptlets. Well-designed tag extension libraries can enable application functionality to be invoked without the appearance of programming.

So in this chapter, we'll look at the basics of writing your own tags and then in the next chapter we'll look at some more advanced examples. So in this chapter we will cover:

  • Tag extension basics
  • The anatomy of a tag extension
  • How to deploy a tag library
  • How to write custom tag extensions

Let's get started then with what tag extensions are all about.

Tag Extension 101

Consider the <jsp:forward> action provided by the JSP specification. This tag dispatches the current request to another page in the current web application. It can be invoked with the following syntax:

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

We can also to add additional parameters to the request before forwarding with an extended usage of <jsp:forward>, which nests one or more <jsp:param> tags within the <jsp:forward> tag:

<jsp:forward page="next.jsp" >
<jsp:param name="image" value="house.gif" />
</jsp:forward>

Tag extensions allow a vast range of new functionality to be added to the JSP language and they can be invoked in a similarly intuitive way. For example, I could create a tag named <wrox:forward>, specify what attributes and subtags, if any, it requires, and implement it to perform a custom action before forwarding. Not only can this be added simply into the web page, it enforces separation of code and presentation, decouples the call from the class that implements the functionality associated with the tag, and can be simply incorporated into a design tool.

The key concepts in tag extensions are:

  • Tag name:
    A JSP tag is uniquely identifed by a combination of prefix (in this case jsp), and suffix (in this case forward), separated by a colon.
  • Attributes:
    Tags may have attributes, which use the XML syntax for attributes. The <jsp:forward> tag above has one attribute (page), while the <jsp:param> attribute has two (name and value). Attributes may be required or optional.
  • Nesting:
    Note how the <jsp:param> subtag is used in the second example above. Tag extensions can detect nested tags at runtime and cooperate. A tag directly enclosing another tag is called the parent of the tag it encloses: in the example above, the <jsp:forward> tag is the parent of the <jsp:param> tag.
  • Body content:
    This is anything between the start and end elements in a JSP tag, excluding subtags. A tag extension can access and manipulate its body content. Neither the <jsp:forward> nor <jsp:param> tags require body content. We will see later an example of a tag that can reverse its body content. It will be invoked like this (the body content is shown in bold):

<examples:reverse>
Able was I ere I saw Elba
</examples:reverse>

The functionality associated with a tag is implemented by one or more Java classes. The tag handler (the class implementing the tag itself) is a JavaBean, with properties matching the tag's XML attributes. A Tag Library Descriptor (TLD) file is an XML document that describes a tag library, which contains one or more tag extensions. The JSP taglib directive must be used to import the tag library's tags in each JSP that wishes to use any of them.

Why, besides a clever syntax, might we choose to use tag extensions rather than JSP beans? Are tag extensions not simply another way of allowing JSP pages to parcel out work to Java classes?

Due to the richer interaction between the hosting JSP page and tag extensions, tag extensions can achieve directly what beans can only achieve in conjunction with scriptlets. Tag extensions may access the PageContext, write output to the output writer, redirect the response, and define scripting variables. As an indication of their power, all the standard JSP actions provided via tags of form <jsp:XXXX> could be implemented using tag extensions. The behavior of tag handlers is configured by their XML attributes and their body content (which can be the result of evaluating JSP expressions at runtime).

Typical uses of tag extensions are:

  • To conceal the complexity of access to a data source or enterprise object from the page (possibly, the page author, who may not be experienced with enterprise data)
  • To introduce new scripting variables into the page
  • To filter or transform tag content, or even interpret it as another language
  • To handle iteration without the need for scriptlets

Tag extensions can be used to deliver a range of functionality limited only by developers' imaginations and sensible programming practice.

Tag extensions differ from beans in that they are common building blocks, not tailored resources for a particular page or group of pages. Tags receive the attributes that control their behavior from the JSP pages using them, not the request to a particular JSP (as in the case of request-bean property mappings). A well-designed tag extension may be used in many JSP pages.

This reusability is particularly important. Since their implementation and interaction with the JSP engine is well defined in the JSP 1.1 specification, libraries of tag extensions can be developed and distributed, on a commercial or open source basis. Generic tags can be developed for particular industries or application types.

Tag extensions, although new to JSP, are a very old concept in dynamic page generation. Products such as Apple's WebObjects and BroadVision have delivered rich functionality through custom tags for years, although in a proprietary context. This experience in the use of custom tags can be valuable to JSP developers.

Tag extensions are a particularly welcome addition to the JSP developer's armory because they are easy to implement. The API surrounding them is relatively simple, and it is possible to use them to achieve results quickly. This is a reflection of the elegance of the design of the tag extension mechanism; in the true Java spirit it delivers rich functionality without excessive complexity.

The examples and most of the discussion in this chapter and the next assume that tag extensions will be used to generate HTML markup. While this is currently their most likely use, tag extensions can be used to generate any content type supported by JSP.

A Simple Tag

Before we look at the API supporting tag extensions and the supporting infrastructure in detail, let's implement a simple tag. The simplest case is a tag without attributes or body content, which outputs some HTML. We'll add some dynamic content to prove that the tag is alive. Say we want to see the following output:

Hello world.
My name is <tag handler implementation class> and it is now <date and time>

We'll call our simple tag hello. Here's how we might use it in a JSP. I've named this simple example hello.jsp. The first line is a declaration used to import the tag library, which we will discuss in detail later:

<%@ taglib uri="/hello" prefix="examples" %>

<html>
<head>
 <title>First custom tag</title>
</head>
<body>
 This is static output.
 <p />
 <i>
  <examples:hello></examples:hello>
 </i>
 This is static output again.
</body>
</html> 

All we need to do to implement the tag is to define a tag handler (a Java class implementing the tag's functionality), and provide the tag library descriptor. We can then import the tag library into any JSP that requires it.

The tag handler class must react to callbacks from the JSP engine when the tag is encountered in JSPs. The most important of these are doStartTag(), called when the opening of the tag is encountered, and doEndTag(), called when the closing tag is encountered. The implementation of HelloTag is quite simple, as most of the work of implementing the custom tag is done by the TagSupport superclass provided by the JSP 1.1 API. Don't worry if some of the details are puzzling: we'll look at this class, as well as the API it uses, in more detail in a moment. Note that the tag has access to the PageContext object of each JSP that uses it.

package tagext;

import java.io.IOException;
import java.util.Date;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

// Implementation of a tag to generate a single piece of HTML
public class HelloTag extends TagSupport {
// This method will be called when the JSP engine encounters the start
// of a tag implemented by this class
public int doStartTag() throws JspTagException {
// This return value means that the JSP engine should evaluate
// the contents and any child tags of this tag
return EVAL_BODY_INCLUDE;
}

// This method will be called when the JSP engine encounters the end
// of a tag implemented by this class
public int doEndTag() throws JspTagException {
String dateString = new Date().toString();
try {
pageContext.getOut().write("Hello world.<br/>");
pageContext.getOut().write("My name is " + getClass().getName() +
             " and it's " + dateString + "<p/>");
} catch (IOException ex) {
throw new JspTagException
     ("Fatal error: hello tag could not write to JSP out");
}

// This return value means that the JSP engine should continue to
// evaluate the rest of this page
return EVAL_PAGE;
}
} // class HelloTag

The tag library descriptor, which we'll name hello.tld, is required to map the tag to the tag handler class and defines the way JSPs may interact with the HelloTag class. The tag library descriptor is an XML document conforming to a DTD specified by Sun Microsystems:

<?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">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>examples</shortname>

<info>Simple example library.</info>

<tag>
 <name>hello</name>
 <tagclass>tagext.HelloTag</tagclass>
 <bodycontent>JSP</bodycontent>
 <info>Simple example</info>
</tag>
</taglib>

The tag's suffix when used in JSPs must be hello, and its prefix is examples.

Note that as a tag library can include any number of tags, we'll add extra <tag> elements to this tag library descriptor for the remaining examples in this chapter.

Continued...


NEXT PAGE



7 RELATED COURSES AVAILABLE
INTRODUCTION TO JAVA PROGRAMMING
The aims of this Java training courses is to understand the role that Java plays on the Internet; describe the be....
JAVA (V1.2): ADVANCED PROGRAMMING
This course teaches the reader to learn, understand and become familiar with the advanced features of Java progra....
INTRODUCTION TO JAVABEANS
To go from the fundamentals of JavaBeans programming to the threshold of Advanced level. Gaining in depth progr....
C++ PROGRAMMING
Object oriented programming is fast becoming the leading software design methodology, with C++ becoming ever more....
C PROGRAMMING
This course is design to provide non-C programmers with the essential skills and knowledge necessary to allow the....
 
1 RELATED JOBS AVAILABLE
JAVA DEVELOPER MANCHESTER
Computer Futures Solutions are seeking a Senior Java Developer for their Manchester based client. You will be joi....
CONTACT US
Thursday 11th March 2010  © COPYRIGHT 2010 - VISUALSOFT