第一部分:JSP中
<%@taglib uri=" /simpleforeachTag " prefix="c" %>
<%@taglib uri=" /simpleforeachTag " prefix="c" %>
<body>
<%
Integer arr[]={1,2,3,4};
//对象类型
request.setAttribute("arr", arr);
%>
<c:SimpleForeach
var="i"
items="${arr }">
${i }
</c:SimpleForeach>
<br/>------------------<br/>
<%
boolean b[]={false,true,false};
//基本数据类型
request.setAttribute("b", b);
%>
<c:SimpleForeach
var="i"
items="${b }">
${i }
</c:SimpleForeach>
<br/>------------------<br/>
<%
Map map=new HashMap();
//双列集合
map.put("aa","111");
map.put("bb","222");
map.put("cc","333");
request.setAttribute("map", map);
%>
<c:SimpleForeach
var="entry"
items="${map }">
${entry.key }=${entry.value }
</c:SimpleForeach>
</body>
第二部分:tld文档
思考:ArrayList Arrays Collection的用法???
第二部分:tld文档
<uri>/simpleforeachTag</uri>
<tag>
<name>
SimpleForeach</name>
<tag-class>cn.itcast.web.simpletag.ForeachTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>
var</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>
items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
第三部分:JAVA代码
public class ForeachTag extends SimpleTagSupport {
p
rivate String var;
private Object items;
private Collection collection;
//无论是单列集合还是双列集合,都转成单列。
public void setItems(Object items) {
this.items = items;
if(items instanceof Collection){ //判断是否是单列
collection=(Collection)items;
}
if(items instanceof Map){
Map map=(Map)items;
collection=map.entrySet();
//将双列Map集合转成单列
}
/*if(items instanceof Object[]){
Object obj=(Object) items;
collection=Arrays.asList(obj);//注意Arrays.asList(参数只能是对象),
}
*/下面代码就能处理所有类型的数组数据
if(items.getClass().isArray()){
this.collection=new ArrayList();
int length=Array.getLength(items);
for(int i=0;i<length;i++){
Object value=Array.get(items, i);
this.collection.add(value);
}
}
}
public void setVar(String var) {
this.var = var;
}
@Override
public void
doTag() throws JspException, IOException {
Iterator it=this.collection.iterator();
while(it.hasNext()){
Object value=it.next();
this.getJspContext().setAttribute(var, value);
this.getJspBody().invoke(null);
}
}
}