|
JSP Custom Tag
Part:
1
2
What is a Custom Tag?
Custom Tag is an action tag defined by the user through the JSP tag extension facility.
It can be used to move JSP page authoring logics and information into a tag Java class, and invoke
it by an action tag that is linked to that class. There are two main advantages of using
custom tags:
- Repeatable JSP page logics and information can be simplified and centralized into a single tag.
For example, we can define a custom tag called <my:copyright/> for producing
the copyright information that need to be used on every page of server.
- Moving complex business logics from the JSP to a tag class, so the JSP page
author can concentrate on the presentation logics only. For example, we can define a
custom tag called <my:userList/> for producing a HTML table filled with a list of users.
The tag class will manage how the put each user into a row, and each user property
into a column.
I am sure that the functionalities provided by custom tags can also be archived by
using JavaBean and scripting elements together. But tags seem to be simpler to use
for many unsophisticated JSP page authors.
"Hello world!" Custom Tag
Before we go into any technical details, let me use a very simple example to show
you the steps to define and use a custom tag.
I want to define a tag called <hy:hello/> to produce the "Hello world!" in the calling
JSP page.
1. Writing the tag class. Here is my first tag class, HelloTag.java, which extends
the TagSupport class provided in the JSP package:
/**
* HelloTag.java
* Copyright (c) 2003 by Dr. Herong Yang. All rights reserved.
*/
import java.io.*;
import javax.servlet.jsp.tagext.*;
public class HelloTag extends TagSupport {
public int doStartTag() {
try {
pageContext.getOut().write("Hello world!");
} catch (IOException e) {
System.err.println(e.toString());
}
return SKIP_BODY;
}
}
2. Installing the tag class. I compiled HelloTag.java with JDK 1.3.1, and servlet.jar
provided by the Tomcat 4.1.18 server. Like the JavaBean class files, tag class files
also need to be installed in the class path of the tomcat server. So I copied
the HelloTag.class to \local\jakarta-tomcat-4.1.18\webapps\root\web-inf\classes directory.
(Continued on next part...)
Part:
1
2
|