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 - UpperTagHandler.java

Here is the tag handler for the custom tag.


package st;

import java.io.StringWriter;
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 {
    @Override
    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 (java.io.IOException 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="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">
  <tlib-version>1.0</tlib-version>
  <short-name>st</short-name>
  <uri>http://www.srikanthtechnologies.com/tags</uri>
  <tag>
    <name>upper</name>
    <tag-class>st.UpperTagHandler</tag-class>
    <body-content>tagdependent</body-content>
  </tag>
</taglib>

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"
   "http://www.w3.org/TR/html4/loose.dtd">

<%@taglib prefix="st" uri="http://www.srikanthtechnologies.com/tags" %>
<html>
    <body>
      <st:upper>Srikanth Pragada</st:upper>
    </body>
</html>

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.