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>
看這麽簡單就可以得到想要的結果,方便吧。