Introduction: Brettmclaughlin continues his JSP best practice series, this time he will use a property to extend the custom timestamp tag (lastmodified), which allows page authors to select their own timestamp format.
The previous issue of JSP best practices describes the basics of using custom tag libraries in JSP pages. In that issue, you can learn how to define a simple tag and make it available to other JSP authors by using the tag library descriptor (Tag libraries descriptor,tld). This week, we'll build on the knowledge you already know about custom tags. The example tag we used last time is very simple and there are some drawbacks. So now we're going to extend the functionality of the tag through custom attributes.
A note on this instance: all the instance code for this issue is based on the lastmodified tag we developed last time. If you haven't read the previous issue in full, you should go back to the previous issue before you continue reading this issue.
Customize "Hello, World"
The most common requirement for JSP tags is to be able to accept data from a page (or page author) and to sound the data. Tag attributes allows us to incorporate this functionality into custom tags.
Give a very simple example, such as a typical "Hello, world" application. It's easy to imagine what it would be like to implement this scriptlet functional custom tag, but how about a little extension of this tag?
In Listing 1 we can see a JSP page fragment, which has a typical "Hello, world!" tag, but this tag includes a property named name.
Listing 1. A simple "Hello, world!" tag
<p>
<examples:hello name="Reader" />
</p>
The Name property creates space for the page author to give the Hello tag the data, in this case the data provided is a person's name, and the application will relay its message to the person. In fact, we have customized "Hello, world"-but how do we define it? Listing 2 shows the Java code to implement the Hello tag:
Listing 2. The code for the Hello tag
package com.ibm.examples;
import java.io.IOException;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class HelloTag extends TagSupport {
// The "person" to say hello to
private String name;
// Accept the attribute data
public void setName(String name) {
this.name = name;
}
public int doEndTag() {
try {
StringBuffer message = new StringBuffer("Hello, ");
message.append(name)
.append("!");
pageContext.getOut().println(message.toString());
} catch (IOException ignored) { }
return EVAL_PAGE;
}