Thursday, September 11, 2008

Writing Simple Taglibs

Writing tag libraries has mainly 3 parts

1 .The tld file defining the tag parameters

2. Java Class Containing the implementation of the Tag

3. Jsp Code Calling the Taglib


1.Tld for Tag

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>oreillySamples</shortname>
<info>OReilly Sample Tag library</info>

<tag>
<name>hello</name>
<tagclass>com.ivy.tags.Hello </tagclass>

<bodycontent>JSP</bodycontent>
<info>
This is a simple hello tag.
</info>

<attribute>
<name>name</name>
<required>false</required>
<rtexpvalue>true</rtexpvalue>
</attribute>


<attribute>
<name>iterations</name>
<required>false</required>
<rtexpvalue>false</rtexpvalue>
</attribute>

</tag>
</taglib>

2.Java Class For the Tag

public class Hello extends BodyTagSupport {
private String name=null;
private int iterations=1;

/**
* Getter/Setter for the attribute name as defined in the tld file
* for this tag - Name & iterations
*/


//core content of the tag needs to be written here

public int doStartTag() throws JspTagException{
try {
JspWriter out = pageContext.getOut();
out.println("<table border=\"1\">");
if (name != null)
out.println("<tr><td> Hello " + name + " </td></tr>");
else
out.println("<tr><td> Hello World <td></tr>");
} catch (Exception ex) {
throw new JspTagException("All is not well in the world." + ex );
}
// Evaluate the body if there is one
return EVAL_BODY_TAG;
}

//For the end part execution

public int doEndTag() throws JspTagException {
try {
JspWriter out = pageContext.getOut();
out.println("</table>");
} catch (Exception ex){
throw new JspTagException("All is not well in the world." + ex);
}
return(EVAL_PAGE);
}

public int doAfterBody() throws JspTagException {
if (iterations >= 1) {
BodyContent body = getBodyContent();
try {
JspWriter out = body.getEnclosingWriter();
out.println(body.getString());
body.clearBody(); // Clear for next evaluation
} catch(IOException ioe) {
throw new JspTagException("Error in Hello tag doAfterBody " + ioe);
}
return(EVAL_BODY_TAG);
} else {
return(SKIP_BODY);
}
}}

3. JSP PAGE

Include the written tld <%@ taglib uri="./sample.tld" prefix="sample" %>

<sample:hello name="userName" iterations="5">
<tr><td><b>Have a nice day</b></td></tr>
</sample:hello>

No comments:

 
Free Domain Names @ .co.nr!