Monday, November 18, 2024
Google search engine
HomeLanguagesJavaCustom Tags with Body in JSP

Custom Tags with Body in JSP

A custom tag can be defined with its body. Body of the tag can be skipped or evaluated as per the requirement. Syntax of custom tags along with its body is given below:

<prefix : suffix> body -content </prefix : suffix>

To create custom tags with the body, the given steps need to be followed.

1. Create tag handler: Implement one of the following interfaces: BodyTag or SimpleTag or extend one of the base classes: BodyTagSupport or SimpleTagSupport.

BodyTag interface: It consists of bodyContent property which can be used to access and modify the body contents of the tag. It provides the following methods to support the evaluation of the tag body.

  • void doInitBody()
  • void setBodyContent(BodyContent b)

In order to evaluate the body, doStartTag() method must return EVAL_BODY_BUFFERED. As soon as EVAL_BODY_BUFFERED is returned, the JSP container creates the BodyContent object and passes it to the setBodyContent() method which sets the bodyContent property of the tag handler. Once, bodyContent is set, doInitBody() is called on the tag handler. 

BodyContent class: It is a subclass of JspWriter. Given below are some useful methods of BodyContent class :

  • void clearBody()
  • Reader getReader()
  • String getString()
  • void writeOut(Writer out)
  • BodyTagSupprt class: It is a base class of the BodyTag interface which provides the default implementation of its abstract methods.
  • SimpleTag interface: It consists of the jspBody property which can be used to access and modify the body contents. The following method is supported by the SimpleTag interface for body evaluation.
  • void setJspBody(JspFragment jspBody)
  • JspFragment getJspBody()

Container creates an object of JspFragment and passes it to setJspBody() method which in turn sets the jspBody property of the tag handler.

JspFragment class: It is an abstract class that encapsulates a portion of JSP code in an object that can be invoked as many times as needed. The definition of the JSP fragment must only contain template text and JSP action elements. In other words, it must not contain scriptlets or scriptlet expressions. The following methods are provided by JspFragment class:

  • JspContext getJspContext()
  • void invoke(Writer out)

SimpleTagSupport class: It is a base class of the Simple tag interface which provide a default implementation of its abstract methods.

2. Create TLD file It consists of a set of related tags along with the description and name of their respective tag handler classes. In order to provide a body in a tag, the <body-content> element must be set to one of the following :

  • scriptless: Body of the tag must not contain scripting elements(scriptlets, scripting expressions, and declarations).
  • JSP: Body of the tag can contain jsp code.
  • tagdependent : Body is treated as plain text.

3. Create a JSP page with taglib directive Provide the taglib directive in the JSP page to specify that the page uses custom tags along with the URI of the tag library.

Syntax:

<%@taglib uri=” ” prefix=” “%>

Example 1 

The following example illustrates the evaluation of the tag body by extending BodyTagSupport class.

DisplayTagHandler.java

Java




package tagHandler;
  
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
  
public class DisplayTagHandler extends BodyTagSupport{
    
    public int doStartTag() throws JspException
    {
        return EVAL_BODY_BUFFERED;
    }
    
    public int doEndTag() throws JspException
    {
        String body=bodyContent.getString();
        try {
            pageContext.getOut().print(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return EVAL_PAGE;
    }
}


CapitalizeTagHandler.java

Java




package tagHandler;
  
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
  
public class CapitalizeTagHandler extends BodyTagSupport {
    
    public int doStartTag() throws JspException
    {
        return EVAL_BODY_BUFFERED;
    }
    
    public int doEndTag() throws JspException
    {
        String body=bodyContent.getString();
        String[] splitArray=body.split(" ");
        String result="";
        int n=splitArray.length;
        for(int i=0;i<n;i++)
        {
            String str=splitArray[i];
            result+=str.substring(0,1).toUpperCase()+str.substring(1)+" ";
        }
        try {
            pageContext.getOut().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return EVAL_PAGE;
    }
}


LowerCaseTagHandler.java

Java




package tagHandler;
  
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
  
public class LowerCaseTagHandler extends BodyTagSupport {
    
    public int doStartTag() throws JspException
    {
        return EVAL_BODY_BUFFERED;
    }
    
    public int doEndTag() throws JspException
    {
        String body=bodyContent.getString();
        String result=body.toLowerCase();
        try {
            pageContext.getOut().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return EVAL_PAGE;
    }
}


UpperCaseTagHandler.java

Java




package tagHandler;
  
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
  
public class UpperCaseTagHandler extends BodyTagSupport{
    
    public int doStartTag() throws JspException
    {
        return EVAL_BODY_BUFFERED;
    }
    
    public int doEndTag() throws JspException
    {
        String body=bodyContent.getString();
        String result=body.toUpperCase();
        try {
            pageContext.getOut().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return EVAL_PAGE;
    }
}


SeparatorTagHandler.java

Java




package tagHandler;
  
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
  
public class SeparatorTagHandler extends BodyTagSupport {
    
    String delimiter;
      
    public String getDelimiter() {
        return delimiter;
    }
    
    public void setDelimiter(String delimiter) {
        this.delimiter = delimiter;
    }
    
    public int doStartTag() throws JspException
    {
        return EVAL_BODY_BUFFERED;
    }
    
    public int doEndTag() throws JspException
    {
        String body=bodyContent.getString();
        String[] splitArray=body.split(" ");
        String result=String.join(delimiter, splitArray);
        try {
            pageContext.getOut().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return EVAL_PAGE;
    }
}


ReplaceTagHandler.java

Java




package tagHandler;
  
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
  
public class ReplaceTagHandler extends BodyTagSupport {
    
    char oldChar;
    char newChar;
      
    public char getOldChar() {
        return oldChar;
    }
    public void setOldChar(char oldChar) {
        this.oldChar = oldChar;
    }
    public char getNewChar() {
        return newChar;
    }
    public void setNewChar(char newChar) {
        this.newChar = newChar;
    }
    public int doStartTag() throws JspException
    {
        return EVAL_BODY_BUFFERED;
    }
    public int doEndTag() throws JspException
    {
        String s=bodyContent.getString();
        String result=s.replace(oldChar, newChar);
        try {
            pageContext.getOut().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return EVAL_PAGE;
    }
}


stringTaglib.tld

XML




<taglib version="2.0" xmlns="http://java.sun.com/xml/j2ee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
  <tlib-version>2.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <tag>
      <name>display</name>
      <tagclass>tagHandler.DisplayTagHandler</tagclass>
      <body-content>scriptless</body-content>
  </tag>
  <tag>
      <name>separate</name>
      <tagclass>tagHandler.SeparatorTagHandler</tagclass>
      <body-content>scriptless</body-content>
      <attribute>
          <name>delimiter</name>
          <required>true</required>
          <rtxprvalue>true</rtxprvalue>
          <type>String</type>
      </attribute>
  </tag>
  <tag>
      <name>capitalize</name>
      <tagclass>tagHandler.CapitalizeTagHandler</tagclass>
      <body-content>scriptless</body-content>
  </tag>
  <tag>
      <name>lower</name>
      <tagclass>tagHandler.LowerCaseTagHandler</tagclass>
      <body-content>scriptless</body-content>
  </tag>
  <tag>
      <name>upper</name>
      <tagclass>tagHandler.UpperCaseTagHandler</tagclass>
      <body-content>scriptless</body-content>
  </tag>
  <tag>
      <name>replace</name>
      <tagclass>tagHandler.ReplaceTagHandler</tagclass>
      <body-content>scriptless</body-content>
      <attribute>
          <name>oldChar</name>
          <required>true</required>
          <rtxprvalue>true</rtxprvalue>
          <type>char</type>
      </attribute>
      <attribute>
          <name>newChar</name>
          <required>true</required>
          <rtxprvalue>true</rtxprvalue>
          <type>char</type>
      </attribute>
  </tag>
</taglib>


index.jsp

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@taglib uri="WEB-INF/stringTaglib.tld" prefix="string" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>String Formatting</title>
   </head>
   <body>
      <string:display>Creating custom tags with body.</string:display>
      <br><br>
      <string:capitalize>Creating custom tags with body.</string:capitalize>
      <br><br>
      <string:lower>Creating custom tags with body.</string:lower>
      <br><br>
      <string:upper>Creating custom tags with body.</string:upper>
      <br><br>
      <string:separate delimiter="...">Creating custom tags with body.</string:separate>
      <br><br>
      <string:replace oldChar="a" newChar="x">Creating custom tags with body.</string:replace>
   </body>
</html>


Output:

string.jsp

 

Example 2

Following example illustrates the evaluation of the tag body by extending SimpleTagSupport class.

StyleTagHandler.java

Java




package tagHandler;
  
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
  
public class StyleTagHandler extends SimpleTagSupport {
    
    int fontSize;
    String fontFace;
    String fontColor;
    
    public int getFontSize() {
        return fontSize;
    }
    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
    }
    public String getFontFace() {
        return fontFace;
    }
    public void setFontFace(String fontFace) {
        this.fontFace = fontFace;
    }
    public String getFontColor() {
        return fontColor;
    }
    public void setFontColor(String fontColor) {
        this.fontColor = fontColor;
    }
      
    public void doTag() throws JspException,IOException
    {
        JspWriter out=getJspContext().getOut();
        StringWriter sw=new StringWriter();
        JspFragment body=getJspBody();
        body.invoke(sw);
        out.print(" <span style=\"font-size:"+fontSize+"px;color:"+fontColor+";font-family:"+fontFace+";\">" );
        out.print(sw.toString());
        out.print("</span>");
    }
}


formatTaglib.tld

XML




<taglib version="2.0" xmlns="http://java.sun.com/xml/j2ee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
  <tlib-version>2.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <tag>
      <name>style</name>
    <tag-class>tagHandler.StyleTagHandler</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
        <name>fontSize</name>
        <required>true</required>
        <rtxeprvalue>false</rtxeprvalue>
        <type>int</type>
    </attribute>
    <attribute>
        <name>fontColor</name>
        <required>true</required>
        <rtxeprvalue>false</rtxeprvalue>
        <type>String</type>
    </attribute>
    <attribute>
        <name>fontFace</name>
        <required>true</required>
        <rtxeprvalue>false</rtxeprvalue>
        <type>String</type>
    </attribute>
  </tag>
</taglib>


format.jsp

html

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@taglib uri="WEB-INF/formatTaglib.tld" prefix="format"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>Format</title>
   </head>
   <body>
      <format:style fontColor="green" fontSize="40" fontFace="Georgia">Styling text using </format:style>
      <format:style fontColor="black" fontSize="50" fontFace="Garamond">Custom Tags in JSP</format:style>
   </body>
</html>


Output:

format.jsp

 

RELATED ARTICLES

Most Popular

Recent Comments