java程序 RepeatSimpleTag.java://放到WEB-INF/classes/jsp2/examples/simpletag
下面
package jsp2.examples.simpletag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.util.HashMap;
import java.io.IOException;
public class RepeatSimpleTag extends SimpleTagSupport
{
private int num;
public void doTag() throws JspException, IOException {
for (int i=0; i<num; i++) {
getJspContext().setAttribute("count", String.valueOf(
i + 1 ) );
getJspBody().invoke(null);
}
}
public void setNum(int num) { //这个用来设置num的值,这个方法将在tld文件中调用
this.num = num;
}
}
-------------------------------------------------
repeatTaglib.tld (标志库描述文件,放在WEB-INF下面的jsp2下面)
<?xml version="1.0" encoding="UTF-8"
?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
web-jsptaglibrary_2_0.xsd" version="2.0">
<description>A tag library exercising SimpleTag handlers.</description>
<tlib-version>1.0</tlib-version>
<short-name>SimpleTagLibrary</short-name>
<uri>/SimpleTagLibrary</uri>
<tag> <!--这里是开始标志描述-->
<name>repeat</name> <!--这里设定的标志名称,供jsp文件调用-->
<tag-class>jsp2.examples.simpletag.RepeatSimpleTag</tag-class>
<!--对应的java文件路径-->
<body-content>scriptless</body-content>
<variable> <!--设置要获取的变量返回值-->
<description>Current invocation count (1 to num)</description>
<name-given>count</name-given>
</variable>
<attribute> <!--设置java类中变量,调用java文件中的setNum()方法-->
<name>num</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag> <!--//这里是结束标志描述-->
</taglib>
------------------------------------------------
repeat.jsp
<%@ taglib prefix="repeattag" uri="/WEB-INF/jsp2/repeatTaglib.tld"
%>
<html>
<body>
<br>
<repeattag:repeat num="5">//向标记库文件中的repeat标记付值
获得返回值:${count} of 5<br>//得到返回结果(java程序中实现了循环)
</repeattag:repeat>
</body>
</html>
看这么简单就可以得到想要的结果,方便吧。