logic:iterate

<logic:iterate>標記用於在頁面中創建一個循環,以此來遍歷如數組、Collection、Map這樣的對象。該標記的功能強大,在Struts應用的頁面中經常使用到。
1、對數組進行循環遍歷
  使用<logic:iterate>標記可以用於遍歷數組,以下是一段示例代碼:

<%
String[] testArray={"str1","str2","str3"};
pageContext.setAttribute("test",testArray);
%>
<logic:iterate id="show" name="test">
<bean:write name="show"/>
</logic:iterate>

在上面的代碼中,首先定義了一個字符串數組,併爲其初始化。接着,將該數組存入pageContext對象中,命名爲test1。然後使用<logic:iterate>標記的name屬性指定了該數組,並使用id來引用它,同時使用<bean:write>標記來將其顯示出來。其結果爲:
str1
str2
str3


  另外,還可以通過length屬性來指定輸出元素的個數。如下面的代碼:
<logic:iterate id="show" name="test" length="2" offset="1">
<bean:write name="show"/>
</logic:iterate>

其中length屬性指定了輸出元素的個數,offset屬性指定了從第幾個元素開始輸出,如此處爲1,則表示從第二個元素開始輸出。所以該代碼的運行結果應當輸出:
str2
str3


  另外,該標記還有一個indexId屬性,它指定一個變量存放當前集合中正被訪問的元素的序號,如:

<logic:iterate id="show" name="test" length="2" offset="1" indexId="number">
<bean:write name="number"/>:<bean:write name="show"/>
</logic:iterate>

其顯示結果爲:
1:str2
2:str3

2、對HashMap進行循環遍歷

<%
HashMap countries=new HashMap();
countries.put("country1","中國");
countries.put("country2","美國");
countries.put("country3","英國");
countries.put("country4","法國");
countries.put("country5","德國");
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對象的鍵和值。其顯示結果爲:
country5:德國
country3:英國
country2:美國
country4:法國
country1:中國

  由結果可看出,它並未按添加的順序將其顯示出來。這是因爲HaspMap是無序存放的。

3、嵌套遍歷

<%
String[] colors={"red","green","blue"};
String[] countries1={"中國","美國","法國"};
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>


  運行效果:
0 red green blue
1 中國 美國 法國
2 喬丹 布什 克林頓

<logic:iterate id="it" name="list" length="2">
<bean write name="it"/><br/>
</logic:iterate>

list 是你要遍例的對象 it是list裏面的元素的類型 ,還有個offset屬性,是用來表示起始位置的,比如,offset=“1”從第二位開始遍歷出值,offset=“0”是默認值 

發佈了24 篇原創文章 · 獲贊 0 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章