Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Sunday, December 2, 2007

How to Create your own tag: a custom tag body in java

///



/java2s
/WEB-INF/java2s.tld



// create File:java2s.tld in the /WEB-INF/
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">



1.0
1.2
Java2s Simple Tags



bodyContentTag
com.java2s.BodyContentTag
JSP

howMany





//compile the following code into WEB-INF\classes\com\java2s
package com.java2s;

import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class BodyContentTag extends BodyTagSupport
{
private int iterations, howMany;

public void setHowMany(int i)
{
this.howMany = i;
}

public void setBodyContent(BodyContent bc)
{
super.setBodyContent(bc);
System.out.println("BodyContent = '" + bc.getString() + "'");
}

public int doAfterBody()
{
try
{
BodyContent bodyContent = super.getBodyContent();
String bodyString = bodyContent.getString();
JspWriter out = bodyContent.getEnclosingWriter();

if ( iterations % 2 == 0 )
out.print(bodyString.toLowerCase());
else
out.print(bodyString.toUpperCase());

iterations++;
bodyContent.clear(); // empty buffer for next evaluation
}
catch (IOException e)
{
System.out.println("Error in BodyContentTag.doAfterBody()" + e.getMessage());
e.printStackTrace();
} // end of catch

int retValue = SKIP_BODY;

if ( iterations < howMany )
retValue = EVAL_BODY_AGAIN;

return retValue;
}
}
// start comcat and load the bodyContent.jsp in browser
<%@ taglib uri="/java2s" prefix="java2s" %>



A custom tag: body content


This page uses a custom tag manipulates its body content.
Here is its output:


  1. java2s.com




No comments: