Creating and Using Custom Tags

This section describes main steps of creating and using custom tags in JSP pages. Each custom tag is supported by a Java tag class that extends the javax.servlet.jsp.tagext.TagSupport class.

Main steps of creating and using a custom tag:

1. Writing the Java tag class using javax.servlet.jsp.tagext.TagSupport as the base class. Here how a tag class, TestTag.java, looks like:

import javax.servlet.jsp.tagext.*;
public class TestTag extends TagSupport {
   public int doStartTag() {...}
   public int doEndTag() {...}
   ...
}

2. Compiling the tag class with the help of the jsp-api.jar provided by the Tomcat server.

3. Installing the compiled tag class to the .\WEB-INF\classes directory on the Tomcat server.

4. Creating the TLD (Tag Library Descriptor) file to define your own tag library with a list of tags and their Java classes. Here is how a TLD file, MyTaglib.tld, looks like:

<?xml version="1.0"?>
<taglib>
<tlib-version>1</tlib-version>
<jsp-version>1.2</jsp-version> 
<short-name>Herong's Tag Library</short-name> 
<tag>
 <name>test</name>
 <tag-class>TestTag</tag-class>
 <body-content>empty</body-content>
</tag>
...
</taglib>

5. Installing the TLD file to the .\WEB-INF\tlds directory on the Tomcat server.

6. Writing a JSP page to use the new custom tag. You need to declare a new namespace for your new TLD file and use the tag as an action element:

<jsp:root xmlns:hy="urn:jsptld:/WEB-INF/tlds/HyTaglib.tld" ...> 
...
<hy:test/>
...

7. Deploying JSP pages to the Tomcat server. You are ready to visit thoes JSP pages.

Last update: 2012.

Table of Contents

 About This Book

 JSP (JavaServer Pages) Overview

 Tomcat 7 Installation on Windows Systems

 JSP Scripting Elements

 Java Servlet Introduction

 JSP Implicit Objects

 Syntax of JSP Pages and JSP Documents

 JSP Application Session

 Managing Cookies in JSP Pages

 JavaBean Objects and "useBean" Action Elements

 Managing HTTP Response Header Lines

 Non-ASCII Characters Support in JSP Pages

 Performance of JSP Pages

 EL (Expression Language)

 Overview of JSTL (JSP Standard Tag Libraries)

 JSTL Core Library

JSP Custom Tags

 What Is Custom Tag?

Creating and Using Custom Tags

 My First Custom Tag - hy:hello

 How Custom Tag Works

 JSP Java Tag Interface

 Custom Tag Attributes

 Multiple Tags Working Together

 File Upload Test Application

 Outdated Tutorials

 References

 PDF Printing Version