首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Struts 1 logic:iterate 標籤詳解:集合與 Map 遍歷實戰

     編輯:Java 相關知識

前言

<logic:iterate> 是 Struts 1 標籤庫中功能最強大、用途最廣的迴圈標籤,能夠遍歷陣列、Collection、Enumeration、Iterator 或 Map 中的所有元素。本文將透過完整範例說明其核心屬性與各種遍歷場景。

1. 遍歷集合

透過 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

2. 遍歷 Map

遍歷 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>

3. 設定被遍歷的變數來源

<logic:iterate> 提供三種方式指定資料來源:

  1. 單純 name:<logic:iterate id="element" name="Animals"> —— 直接從範圍變數取得集合。
  2. name + property:<logic:iterate id="element" name="catelog" property="items"> —— 從 JavaBean 的屬性取得集合。
  3. collection:<logic:iterate id="header" collection="<%= request.getHeaderNames() %>"> —— 直接使用運行時運算式結果。

4. 從 JavaBean 讀取資料並遍歷

典型流程:

  1. 在 JSP 以 <jsp:useBean> 引入含有集合屬性的 Bean。
  2. 使用 <logic:iterate> 指定 name(Bean id)與 property(集合屬性名)。
  3. 迴圈內透過 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
        // ...
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved