Srikanth Technologies

Processing Body Of Custom Tag In JSP 2.0

In this blog, I show how to process body of a custom tag in JSP 2.0, which introduced a simple tag model. I create a tag that takes a string as the content of the body and writes it to output after converting it to uppercase.

In order to process the body of the custom tag follow the steps given below:

Tag Handler -

Here is the tag handler for the custom tag.

package st;

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

public class UpperTagHandler extends SimpleTagSupport {
    public void doTag() throws JspException {
        JspWriter out = getJspContext().getOut();

        try {
            JspFragment f = getJspBody();  // get body

            StringWriter sw = new StringWriter();
            if (f != null) 
                 f.invoke(sw);  // write into StringWriter

            // take contents from StringWriter and convert to uppercase and then write to out
            out.println( sw.getBuffer().toString().toUpperCase());

        } catch ( ex) {
            throw new JspException("Error in UpperTag tag", ex);

Entries in .TLD file

In order to declare the custom tag, add the following entries into st.tld.

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Using custom tag

Here is a .jsp to use custom tag to convert the body to uppercase.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

<%@taglib prefix="st" uri="" %>
      <st:upper>Srikanth Pragada</st:upper>

Run .jsp to test the custom tag. You can change body-content of the custom tag to scriptless almost with the same effect. The difference between scriptless and tagdepdendent is; tagdependent doesn't process the nested tags such as <jsp:include> and instead sends them as they are to client, whereas scriptless processes them also and sends the result to client.

Post Your Comment


Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :


Posted By shanthi On 31-May-10 11:54:24 AM

sir please give few examples that make use of attributes .

Posted By Abhijit Sarkar On 21-Feb-11 08:44:25 AM

Good simple example. However, there is one scope of improvement and one technically incorrect statement:

Scope of improvement:
can be easily changed to
which eliminates one JspWriter reference and a redundant call to sw.getBuffer().

Technically incorrect statement:
"Tag entry in .tld must specify the body-content as tagdependent"

This can and should more ideally be "scriptless". Check out for details.