How do I create a tag using SimpleTagSupport that uses the tag body?
Author: Deron Eriksson
Description: This Java tutorial describes how to create a custom tag using SimpleTagSupport that utilizes the text in the tag body.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20

In another tutorial, we saw how we could create a tag handler by extending the SimpleTagSupport class and implementing the doTag() method. If we'd like to pass information to a tag handler via the body of a tag, we can access that information via the following:

JspFragment body = getJspBody();

We get a JspFragment and call the invoke() method on it with a writer as a parameter. This basically writes the text in the body to the writer.

This is illustrated in the HeaderTag class. This class takes text input from the body of a tag and creates an HTMLW header out of the text. It sets it to h1, h2, or h3 based on input from an optional attribute (specified in the accompanying TLD file).

package test;


import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class HeaderTag extends SimpleTagSupport {

	private int headerSize = 1;

	public void setHeaderSize(int headerSize) {
		this.headerSize = headerSize;

	public void doTag() throws JspException {
		try {
			if (headerSize < 1) {
				headerSize = 1;
			} else if (headerSize > 3) {
				headerSize = 3;
			PageContext pageContext = (PageContext) getJspContext();
			JspWriter out = pageContext.getOut();

			StringWriter sw = new StringWriter();
			sw.append("<h" + headerSize + ">");

			JspFragment body = getJspBody();

			sw.append("</h" + headerSize + ">");
		} catch (IOException e) {


I created the following TLD file and placed it in WEB-INF/tlds. It defines our tag with the name 'header'.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "">

	<description>This is a demonstration tag library</description>

		<description>This tag is for displaying headers</description>


The index.jsp file references the test.tld via its uri. This JSPW tests our tag in four ways with different bodies and different sizes.


<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@ taglib prefix="mytest" uri=""%>

<mytest:header>This is a test</mytest:header>

<mytest:header headerSize="1">I'm still testing</mytest:header>

<mytest:header headerSize="2">The test continues</mytest:header>

<mytest:header headerSize="3">The test is over</mytest:header>

If we hit the index.jsp in a browser, we see the following:

index.jsp in web browser