Example of BodyTag

In this post, you will learn:

  • Practical use of BodyTag?

Practical example of BodyTag:

To demonstrate the example of BodyTag, I have created a custom tag which receives its body contents from the tag processor and change the case of body text. Here is the source code of the Tag and other application compoenents:

The CaseChangerTag class:

package com.techmentro.learningpad;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.*;

public class CaseChangerTag extends BodyTagSupport {

	String target;
	
	public void setTarget (String t)
	{
		target=t;
	}
		
	public int doEndTag()
	{
		JspWriter out=pageContext.getOut();
		String body=bodyContent.getString();
		String str;
		if(target.equalsIgnoreCase("lower"))
			str=body.toLowerCase();
		else
			str=body.toUpperCase();
		try{
			out.println(str+"<br/>");
		}
		catch(Exception ex)
		{
			System.out.println(ex);
		}
		return EVAL_PAGE;	
	}
	
}

Two things should be noted in the implementation of CaseChanger class. First, it extends BodyTagSupport class. Second, It relies on the doStartTag() method overridden by BodyTagSupport to return EVAL_BODY_BUFFERED.

The TLD file:


<taglib>
<uri>techmentro/tags</uri>

<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>

<tag>
<name>changeCase</name>
<tag-class>com.techmentro.learningpad.CaseChangerTag</tag-class>
<attribute>
<name>target</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

The index.jsp:

<%@ taglib uri="techmentro/tags" prefix="tm" %>

<tm:changeCase target="upper">
it will be converted to upper case.
</tm:changeCase>

<tm:changeCase target="lower">
IT WILL BE CONVERTED TO THE UPPER CASE.
</tm:changeCase>

Output:

IT WILL BE CONVERTED TO UPPER CASE.

it will be converted to lower case.


Example Source Code

  • zip BodyTag
    File size: 7 KB Downloads: 210
If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

7 thoughts on “Example of BodyTag

  1. Very good Knowledgeable persion in india.i think he is providing best tranning and best concept in java..i have also read java from here..

    He is God of JAVA
    regards
    Ajay kumar
    sunday(weekend batch)

  2. Hii Sir , Sir what i do to clear the console in java , like a clrscr(); used in c/c++ languages to clear the console

  3. Neeraj Sir : One of the best Great java training personality over the India.

    Thanks a lot by bottom of my heart to Neeraj Sir.

    Regards,
    Ishtyaqe Ahmad

Leave a Reply

Your email address will not be published. Required fields are marked *