June 26, 2011

Creating a JSP custom tag in a custom tag library (TLD)

To create your own JSP tag described in your own custom Tag Library Descriptor (TLD), do the following steps,

1) Create a Java class that will do the work of the tag when the tag is encountered in the JSP - MyTagHandler.java - in the src folder of the web application

package info.icontraining.jsp;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class MyTagHandler extends SimpleTagSupport {

   private String value;
 
   public void setValue(String value) {
      this.value = value;
   }
 
   public String getValue() {
      return this.value;
   }
 
   public void doTag() throws JspException, IOException {
      getJspContext().getOut().write("Output from tag: ");
      getJspContext().getOut().write("Value is " + getValue());
   }
}

2) Create a TLD file - mytld.tld - in the WebContent/WEB-INF folder of the web application with the following configuration for the tag

<?xml version="1.0" encoding="UTF-8" ?>

<taglib xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">
    
    <description>Test description</description>
    <display-name>My TLD</display-name>
    <tlib-version>1.1</tlib-version>
    <short-name>mine</short-name>
    <uri>myUriForMyTLD</uri>
    
    <tag>
        <description>My Tag Description</description>
        <name>testTag</name>
        <tag-class>info.icontraining.jsp.MyTagHandler</tag-class>
        <body-content>empty</body-content>
        <attribute>
              <description>My attribute description</description>
              <name>value</name>
              <required>true</required>
              <rtexprvalue>false</rtexprvalue>
        </attribute>
    </tag>
</taglib>

3) Create a JSP - myTagTest.jsp - and add it to the WebContent folder of the web application with the following code

<%@ taglib prefix="mine" uri="myUriForMyTLD" %>

<html>
<body>

<mine:testTag value="something" />

</body>
</html>

4) Test the code with the following URL in the browser,

http://localhost:8080/WebAppName/myTagTest.jsp

No comments:

Post a Comment