Quick Hack for the Impatients: JSP Custom Tag

Posted on January 6, 2010

0


Introduction

Source code from this posting was taken fromhttp://java.sun.com/developer/technicalArticles/xml/WebAppDev3/ with some minor replacement needed for Apache Tomcat 6.0.20 (latest as of this date) and more details on how to run the application.

Purpose of Application

This application is used as a showcase for jsp custom tag. Its functionality is create custom tag for jsp to display string in lowercase.

Directory Structure and Files

[bpdp@bpdp-arch webapps]$ tree customtags/
customtags/
|-- WEB-INF
|   |-- classes
|   |   `-- tags
|   |       |-- ToLowerCaseTag.class
|   |       `-- ToLowerCaseTag.java
|   |-- mytaglib.tld
|   `-- web.xml
`-- coba.jsp

3 directories, 5 files
[bpdp@bpdp-arch webapps]$

We created customtags directory under webapps (which is needed for an application to be executed by Tomcat).  Pay attention to file mytaglib.tld, this file is used as tag lib descriptor to describe descriptor for taglib.

Files

ToLowerCaseTag.java

package tags;

import java.io.*;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class ToLowerCaseTag extends BodyTagSupport {
  public int doAfterBody() throws JspException {
    try {
      BodyContent bc = getBodyContent();
      // get the bodycontent as string
      String body = bc.getString();
      // getJspWriter to output content
      JspWriter out = bc.getEnclosingWriter();
      if(body != null) {
        out.print(body.toLowerCase());
      }
    } catch(IOException ioe) {
      throw new JspException("Error: "+ioe.getMessage());
    }
    return SKIP_BODY;
  }
}

web.xml

<web-app>
  <taglib>
    <taglib-uri>mytags</taglib-uri>
    <taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
  </taglib>
</web-app>

mytaglib.tld

<?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">
<!-- a tag library descriptor -->
<taglib>
  <tlibversion>1.0</tlibversion>
  <jspversion>1.1</jspversion>
  <shortname>first</shortname>
  <uri></uri>
  <info>A simple tab library for the examples</info>
  <tag>
    <name>tolowercase</name>
    <tagclass>tags.ToLowerCaseTag</tagclass>
    <bodycontent>JSP</bodycontent>
    <info>To lower case tag</info>
  </tag>
</taglib>

coba.jsp

<%@ taglib uri="mytags" prefix="first" %>
<HTML>
  <HEAD>
    <TITLE>Body Tag</TITLE>
  </HEAD>
  <BODY bgcolor="#ffffcc">
    <first:tolowercase>
      Welcome to JSP Custom Tags Programming.
     </first:tolowercase>
  </BODY>
</HTML>

Notes:

From  all of the files above, you should know the relationship between <%@ taglib uri=”mytags” prefix=”first” %> (in coba.jsp) with mytags (in web.xml).

Run Application

To run this application, type the URL: http://server:8080/customtags/coba.jsp

Here’s the screenshot:

Posted in: Java, Teknologi Web