Simple tag handler

A simple tag handler is a subclass of javax.servlet.jsp.tagext.SimpleTagSupport that is made available to the WebApp by a TDL file and could be called from a JSP page that uses the tablib directive to reference to the TDL as any other tag.

Let's see a first very simple tag handler.

First step is creating a class that extends SimpleTagSupport and overrides its doTag() method. Here the doTag() would just ouput some text:
package ch10;

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

public class SimpleTagTest extends SimpleTagSupport {
    @Override
    public void doTag() throws JspException, IOException {
        getJspContext().getOut().print("What a silly custom tag!");
    }
}
Now we create a TLD in WEB-INF, simple.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
        version="2.0">
    <tlib-version>1.2</tlib-version>
    <uri>simpleTags</uri>
    <tag>
        <description>a first very simple tag handle</description>
        <name>simple</name>
        <tag-class>ch10.SimpleTagTest</tag-class>
        <body-content>empty</body-content>
    </tag>
</taglib>
Now we can use our custom tag in a JSP page:
<%@ taglib prefix="st" uri="simpleTags" %>
<!-- ... -->
<st:simple/>
A custom tag that has a body could be written quite easily. The doTag() calls the invoke() method on the JspFragment object returned by the getJspBody:
package ch10;

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

public class SimpleTagTest2 extends SimpleTagSupport {
    @Override
    public void doTag() throws JspException, IOException {
        if(getJspBody() != null)
            getJspBody().invoke(null);
        else
            getJspContext().getOut().print("No body in this tag");
    }
}
It could happen the JSP page call our tag with no body so, before using the JspFragment, we have to ensure it is not null - otherwise we are going to get a big fat exception.

We add in our TLD the declaration for the new tag, specifying that we expect a scriptless body content:
<tag>
    <description>marginally better use of a custom tag</description>
    <name>simple2</name>
    <tag-class>ch10.SimpleTagTest2</tag-class>
    <body-content>scriptless</body-content>
</tag>
Now we can modify the JSP page to use our new tag too. We test it with and without a body:
<!-- ... -->
<st:simple2>This is the text I want to display</st:simple2>
<st:simple2 />
Much more stuff on Simple tag handlers in chapter ten of Head First Servlet and JSP.

No comments:

Post a Comment