这东西是我一见钟情的,嘿嘿!一开始就引起了我的注意,每次见到它我都很激动,所以我要好好享受享受它了,把它弄的透透的,O(∩_∩)O哈哈~
<logic:iterate>是logic标签库中最复杂的标签,也是用途最广的标签,它能够在一个循环中遍历数组,Collection,Enumeration,Iterator或Map中的所有元素。(嘿嘿!不知道collection,Enumeration是什么,等会查查去)
1、遍历集合
<%
Vector animals=new Vector();
animals.addElement("dog");
animals.addElement("cat");
animals.addElement("bird");
animals.addElement("chick");
request.setAttribute("Animals",animals);
%>
<logic:iterate id="element" name="Animals">
</logic:iterate>
以上代码先定义一个vector类型的集合变量Animals,它存放在request范围内,接下来<logic:iterate>在一个循环中遍历Animals集合中的所有元素,每次检索到一个元素,就把它命名为"element",并存放在page范围内。<bean:write name="element"/>用于输出每个元素的内容。
<logic:iterate id="element" name="Animals" IndexId="index" offset="1" length="2">
</logic:iterate>
length属性指定需要遍历的元素的数目,如果没有设置length属性,就遍历集合中的所有元素,offset属性指定开始遍历的起始属性,默认值是"0",表示从集合的第一的元素开始。indexId属性定义代表当前遍历元素序号的变量,这个变量被存放在page范围内,可以被标签主体的<bean:write>标签访问。
2、遍历Map
<%
%>
<logic:iterate id="element" indexId="ind" name="Months">
</logic:iterate>
如果HashMap中的每个元素的value是集合对象,则可以采用嵌套的<logic:iterate>遍历集合中的所有对象:
<%
%>
<logic:iterate id="element" name="catalog" indexId="ind">
</logic:iterate>
3、设置被遍历的变量
可以通过以下方式来设置需要遍历的变量。
1)设置name属性,name属性指定需要遍历的集合或Map
2)设置name属性和property属性,name属性指定一个javaBean,property指定一个javaBean的一个属性,这个属性为需要变量的集合和Map
<logic:iterate id="header" collection="<%=request.getHeaderNames()%>">
</logic:iterate>