Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Sunday, December 2, 2007

java code for A custom tag: iteration




/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




iterationTag
com.java2s.IterationTag
JSP

howMany




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

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/* This tag iterates a number of times, as specified by
its "howMany" attribute.
*/

public class IterationTag extends TagSupport
{
// Code to implement the "howMany" attribute

private int howMany;
public int getHowMany()
{
return howMany;
}
public void setHowMany(int i)
{
howMany = i;
}

public int doStartTag() throws JspException
{
return EVAL_BODY_INCLUDE;
}

private int countIterations = 0;
public int doAfterBody() throws JspException
{
int retValue = (countIterations >= (howMany - 1)) ? SKIP_BODY
: EVAL_BODY_AGAIN;

try
{
JspWriter out = pageContext.getOut();

if ( countIterations < howMany)
{
int nextNumber = (int) (Math.random() * 10);
out.println(nextNumber + "
");
}
}
catch (IOException e)
{
System.out.println("Error in IterateTag.doAfterBody()");
e.printStackTrace();
throw new JspException(e); // throw the error to the error page (if set)
} // end of try-catch

countIterations++;
return retValue;
} // end of doAfterBody()
} // end of class IterationTag



// start comcat and load the following jsp page in browser
<%@ taglib uri="/java2s" prefix="java2" %>



A custom tag: iteration


output:




Here is a random number:


No comments: