IterateTag.java
package tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
/**
* @作者 :goby
* @创建时间:2009-6-14 下午04:47:43
* @更新时间:$Date$
*/
public class IterateTag extends TagSupport {
String name;
String[] items;
int i = 1;
public void setName(String name) {
this.name = name;
}
public void setItems(String[] items){
this.items = items;
}
/* (non-Javadoc)
* @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
*/
@Override
public int doStartTag() throws JspException {
// TODO Auto-generated method stub
if(items!=null && items.length>0){
pageContext.setAttribute(name, items[0]);
//把标签体的执行结果插入到输出流中
return EVAL_BODY_INCLUDE;
}
return super.doStartTag();
}
// 不再重复执行标签内容
@Override
public int doAfterBody() throws JspException {
if(i<items.length){
pageContext.setAttribute(name, items[i]);
i++;
return EVAL_BODY_AGAIN;//重复执行标签内容
}else{
return SKIP_BODY; //不再重复执行标签内容
}
}
}
tag.tld
<?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"> <tlib-version>1.0</tlib-version> <short-name>it315</short-name> <uri>/taglib</uri> <tag> <name>iterate</name> <tag-class>tag.IterateTag</tag-class> <attribute> <name>name</name> <requried>true</requried> </attribute> <attribute> <name>items</name> <requried>true</requried> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
index.jsp
<%@ page contentType="text/html; charset=gb2312" %>
<%@ taglib uri="/taglib" prefix="it315" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Hello</title>
</head>
<body>
<br>
iterate:
<br>
<% String[] books = {"dsdeeeee","123","ss","dd"}; %>
<it315:iterate name="bookname" items="<%=books %>">
<%=pageContext.findAttribute("bookname") %>
${bookname}<br>
</it315:iterate>
</body>
</html>