3、迭代标签<c:foreach items=”” var=””>
Jsp的页面:< c:foreach items="${list}" var="str">
${str}
</c:foreach>
Tld文件的描述:<tag>
<name>foreach</name>
<tag-class>com.hbsi.web.tag.ForEachTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
标签处理器:public class ForEachTag extends SimpleTagSupport {
private Object items;
private String var;
public void setItems(Object items) {
this.items = items;
}
public void setVar(String var) {
this.var = var;
}
@Override
public void doTag() throws JspException, IOException {
//得到集合对象
Collection collection=null;
if(items instanceof Map){
Map map=(Map)items;
//两列集合转换成单列;映射
collection=map.entrySet();
}else if(items instanceof Collection){
collection=(Collection)items;//集合
}else if(items.getClass().isArray()){
collection=new ArrayList();
int length=Array.getLength(items);
for(int i=0;i<length;i++){
collection.add(Array.get(items, i));
}
}
Iterator it=collection.iterator();
while(it.hasNext()){
Object obj=it.next();//一个元素
this.getJspContext().setAttribute(var,obj);
this.getJspBody().invoke(null);
}
}
}