<logic:iterate> 是 Struts 1 標籤庫中功能最強大、用途最廣的迴圈標籤,能夠遍歷陣列、Collection、Enumeration、Iterator 或 Map 中的所有元素。本文將透過完整範例說明其核心屬性與各種遍歷場景。
透過 name 指定儲存在某範圍(request、session 等)中的集合物件,id 指定每次迴圈取出元素在 page 範圍內的變數名稱。
<%
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">
<bean:write name="element" /><br/>
</logic:iterate>
輸出: Dog / Cat / Bird / Chick(各換行)
常用屬性補充:
length:限制遍歷元素數量,未設定則遍歷全部。offset:起始索引(預設 0)。indexId:將目前索引存入 page 範圍,供巢狀標籤使用。<logic:iterate id="element" name="Animals" indexId="index" offset="1" length="2">
<bean:write name="index" />. <bean:write name="element" /><br/>
</logic:iterate>
輸出:1. Cat / 2. Bird
遍歷 Map 時,每個元素為一組 key/value。可搭配 <bean:write> 分別輸出。
<logic:iterate id="element" name="months" indexId="ind">
<bean:write name="ind" />.
<bean:write name="element" property="key" />:
<bean:write name="element" property="value" /><br/>
</logic:iterate>
若 Map 的 value 為集合,可使用巢狀 <logic:iterate> 深入遍歷:
<logic:iterate id="entry" name="catelog" indexId="ind">
<bean:write name="ind" />.
<bean:write name="entry" property="key" />:
<logic:iterate id="elementValue" name="entry" property="value" offset="1" length="3">
<bean:write name="elementValue" />
</logic:iterate><br/>
</logic:iterate>
<logic:iterate> 提供三種方式指定資料來源:
<logic:iterate id="element" name="Animals"> —— 直接從範圍變數取得集合。<logic:iterate id="element" name="catelog" property="items"> —— 從 JavaBean 的屬性取得集合。<logic:iterate id="header" collection="<%= request.getHeaderNames() %>"> —— 直接使用運行時運算式結果。典型流程:
<jsp:useBean> 引入含有集合屬性的 Bean。<logic:iterate> 指定 name(Bean id)與 property(集合屬性名)。id 取得單一元素,再用 <bean:write> 輸出其屬性。<jsp:useBean id="articleClasses" class="com.GetArticleClasses" />
<logic:iterate id="aClasses" name="articleClasses" property="coll">
<html:link paramId="classId" paramName="aClasses" paramProperty="classId">
<bean:write name="aClasses" property="className" />
</html:link><br/>
</logic:iterate>
Bean 範例:
public class GetArticleClasses {
private Collection coll;
public Collection getColl() { return coll; }
public GetArticleClasses() {
coll = new ArrayList();
// JDBC 查詢資料庫,將每筆記錄封裝為 ArticleClass 物件加入 coll
// ...
}
}