首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

Struts 2 標籤庫實戰:append 標籤合併集合與 generator 標籤生成迭代器

     編輯:MySQL 資料庫相關知識

Struts 2 提供豐富的標籤庫簡化視圖層開發。本文聚焦兩個實用標籤:<s:append> 用於合併多個集合為單一迭代器,<s:generator> 用於從字串動態生成迭代器,避免在 Action 中硬編碼列表。透過完整的 Action、JSP、配置檔範例,示範從開發到部署的全流程。

一、append 標籤:合併多個集合

核心用法


    
    
    


    
  • 需兩個以上 <s:param> 指定來源集合(List/Set/Array)。
  • var 指定合併後迭代器的變數名,供 <s:iterator> 使用。
  • 合併順序:先後參數順序,元素依序追加(非去重)。

完整範例:員工與外包商名單合併

1. Action 類

package com.example.struts2;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;

public class EmployeeAction extends ActionSupport {
    private List employees;
    private List contractors;

    public String execute() {
        employees = new ArrayList<>();
        employees.add(new Employee("George", "Recruitment"));
        employees.add(new Employee("Danielle", "Accounts"));
        employees.add(new Employee("Melissa", "Recruitment"));
        employees.add(new Employee("Rose", "Accounts"));

        contractors = new ArrayList<>();
        contractors.add(new Employee("Mindy", "Database"));
        contractors.add(new Employee("Vanessa", "Network"));
        return SUCCESS;
    }
    // getter/setter 略
    public static class Employee {
        private String name, department;
        public Employee(String name, String department) { this.name = name; this.department = department; }
        public String getName() { return name; }
        public String getDepartment() { return department; }
    }
}

2. JSP 視圖

<%@ taglib prefix="s" uri="/struts-tags" %>

Employees and Contractors Merged
,

3. struts.xml


    
    
        
            /employee.jsp
        
    

二、generator 標籤:動態生成迭代器

核心用法


    
        
  • val:逗號分隔的字串(或 OGNL 表達式)。
  • separator:分隔符,預設逗號。
  • count:取前 N 個元素,省略則取全部。
  • 體內可直接用 <s:iterator> 遍歷生成的值。

完整範例:彩虹顏色列表

1. Action 類(極簡)

package com.example.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
    public String execute() { return SUCCESS; }
}

2. JSP 視圖

<%@ taglib prefix="s" uri="/struts-tags" %>

Generator Tag Example

Rainbow Colours:


3. struts.xml


    
        
            /hello.jsp
        
    

三、部署與驗證

  1. 專案右鍵 → Export → WAR File。
  2. 部署 WAR 到 Tomcat webapps 目錄。
  3. 啟動 Tomcat,訪問:
    • https://localhost:8080/ContextPath/employee.action(append 範例)
    • https://localhost:8080/ContextPath/hello.action(generator 範例)

四、進階提示

  • <s:append> 合併後的迭代器為一次性,不可重複遍歷;若需多次使用,請在 Action 中預先合併為 List。
  • <s:generator> 適合靜態/半靜態選項(下拉選單、單選按鈕組),動態業務資料仍建議在 Action 準備 List。
  • Struts 2.5+ 建議使用 <s:set> 搭配 OGNL 表達式替代部分標籤用法,語法更統一。

五、總結

append 解決多集合合併顯示需求,generator 解決簡單列表硬編碼問題。兩者皆屬視圖層輔助標籤,善用可減少 Action 樣板代碼,保持視圖邏輯清晰。實戰中請根據資料來源動態性選擇:動態資料在 Action 準備,靜態選項用 generator,多來源聚合用 append。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved