Iterate主要用來處理在頁(yè)面上輸出集合類,集合一般來說是下列之一: 1、 java對(duì)象的數(shù)組 2、 ArrayList、Vector、HashMap等
該標(biāo)記的功能強(qiáng)大,在Struts應(yīng)用的頁(yè)面中經(jīng)常使用到。
iterate標(biāo)記 : id 腳本變量的名稱,它保存著集合中當(dāng)前元素的句柄。 name 代表了你需要疊代的集合,來自session或者request的屬性。 type 是其中的集合類元素的類型
bean的write標(biāo)記是用來將屬性輸出的,name用來匹配iterate的id,property用來匹配相應(yīng)類的屬性
1、對(duì)數(shù)組進(jìn)行循環(huán)遍歷
<table width="100%"> <logic:iterate type=" example.User "> <tr><td width="50%"> name: <bean:write property="name"/> <td/><td width="50%"> password: <bean:write property="password"/> </td> </tr> </logic:iterate> </table>
另外,還可以通過length屬性來指定輸出元素的個(gè)數(shù),offset屬性指定了從第幾個(gè)元素開始輸出。
<% String[] testArray={"str1","str2","str3"}; pageContext.setAttribute("test",testArray); % <logic:iterate id="show" name="test"> <bean:write name="show"/> </logic:iterate> <br> <logic:iterate id="show" name="test" length="2" offset="1"> <bean:write name="show"/> </logic:iterate>
結(jié)果: str1 str2 str3
str2 str3
另外,該標(biāo)記還有一個(gè)indexId屬性,它指定一個(gè)變量存放當(dāng)前集合中正被訪問的元素的序號(hào) <logic:iterate length="2" offset="1" indexId="number"> <bean:write name="number"/>:<bean:write name="show"/> </logic:iterate> 其顯示結(jié)果為: 1:str2 2:str3
2 對(duì)HashMap進(jìn)行循環(huán)遍歷 程序代碼<% HashMap countries=new HashMap(); countries.put("country1","中國(guó)"); countries.put("country2","美國(guó)"); countries.put("country3","英國(guó)"); countries.put("country4","法國(guó)"); countries.put("country5","德國(guó)"); pageContext.setAttribute("countries",countries); %> <logic:iterate id="country" name="countries"> <bean:write name="country" property="key"/>: <bean:write name="country" property="value"/> </logic:iterate> 在bean:write中通過property的key和value分別獲得HaspMap對(duì)象的鍵和值。其顯示結(jié)果為: country5:德國(guó) country3:英國(guó) country2:美國(guó) country4:法國(guó) country1:中國(guó) 由結(jié)果可看出,它并未按添加的順序?qū)⑵滹@示出來。這是因?yàn)镠aspMap是無序存放的。
3、嵌套遍歷 程序代碼: <% String[] colors={"red","green","blue"}; String[] countries1={"中國(guó)","美國(guó)","法國(guó)"}; String[] persons={"喬丹","布什","克林頓"}; ArrayList list2=new ArrayList(); list2.add(colors); list2.add(countries1); list2.add(persons); pageContext.setAttribute("list2",list2); %> <logic:iterate id="first" name="list2" indexId="numberfirst"> <bean:write name="numberfirst"/> <logic:iterate id="second" name="first"> <bean:write name="second"/> </logic:iterate> <br> </logic:iterate>
|