logic:Iterator標簽(以下簡稱“該標簽”)是Struts里非常常用的一個標簽,其作用在于循環(huán)顯示給定容器對象中的值。
如此常用的標簽,其源代碼當然需要拿出來研究一下,以下列舉幾條研究成果:
1、該標簽內部使用Collection來表示給定的容器,所有的給定容器對象(如ArrayList,Map等)都會被其轉化成為Collection,Collection實際就是Map和List的父類。
2、該標簽自己維護循環(huán)索引,不用程序員管理索引
3、該標簽常見的幾個屬性如下:name、property、scope、id
對應Struts給出的Api說明如下:
name:包括要遍歷Collection的Jsp頁面的bean的名字(如果property沒有被定義),或者是那些通過getter方法獲得屬性的Jsp中的Bean的名字,這些getter方法返回的是Collection(如果property定義了)。
property:在name命名的Jsp bean中定義的屬性的名字,通過getter方法返回一個Collection
scope:指示到哪里去尋找name為名字的bean,如果沒有定義缺省為"any scope"
id:如果Collection非空的話,在每次遍歷時候Collection中每個元素的名字。
其中除了id每個元素均為Rt expr,這兒的rt expr的意思就是Run Time Expression。明確的說就是,如果你對一個Attribute的<rtexprvalue>指定為true,你就可以在這樣的屬性中使用<%=%>之類的東東。這個配置文件在tld中。
只有id是必須要說明的。
關于Api說明的說明:
id只是一個臨時標識,在下面的<bean:write里面出現的name屬性要和id一致才能打印出<bean:write的property,而此property就是在iterator中的屬性。
舉例說明
以下代碼生成一個階梯狀表格
系統(tǒng) 資源 操作
soft3
res3
opt3
soft12
res12
opt1211
soft11
res11
opt1111
在此之前傳來一個request.getAttribute("userPurview"),所以有在第一個logic中的userPurview,就是在這個request里面尋找userPurview
返回的是一個list
<table width="300" border="0">
<tr><td>系統(tǒng)</td>
<td>資源</td>
<td>操作</td>
</tr>
<logic:iterate id="targetSys" name="userPurview" scope="request"> //這個id可以隨便起名,但是要注意下文使用的一致性
<tr bgcolor="#cccccc"><td height="21" class="unnamed2">
<bean:write name="targetSys" property="cn"/> //此處name和上面id保持一致,property就是第一個list里面的元素
</td>
<td height="21" class="unnamed2"> </td>
<td height="21" class="unnamed3"> </td>
</tr>
<logic:iterate id="targetRes" name="targetSys" property="purviewResList">
<tr><td height="21" class="unnamed2"> </td><td height="21" class="unnamed5">
<bean:write name="targetRes" property="cn"/>
</td>
<td height="21" class="unnamed6"> </td>
</tr>
<logic:iterate id="targetOpr" name="targetRes" property="purviewOprList">
<tr><td height="21" class="unnamed4"> </td><td height="21" class="unnamed4"> </td>
<td height="21" class="redzi">
<bean:write property="cn" name="targetOpr"/></td>
</tr>
</logic:iterate>
</logic:iterate>
</logic:iterate>
</table>
結論:
多級迭代和單層差不多,唯一注意的就是id和<bean:write中的name的對應,上級logic的id與下級logic的name對應,并且取出來的要是個Collection,name和id不一定實際需要這個bean,都是虛擬的。