Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

WebWork 檔案上傳實作:利用 FileUploadInterceptor 實現零配置資料綁定

編輯:XP 系統應用技巧

WebWork(現 Struts 2 前身)以 OGNL 強大的資料綁定聞名,2.1.5 版起內建 FileUploadInterceptor,讓 Action 直接接收 java.io.File 物件,無需手動處理 request.getParameter 或 DTO,極大簡化檔案上傳開發。

Action 程式碼範例
JSP 上傳表單範例

核心實作

1. Action 類別

private File myFile;
private String myFileFileName; // 原始檔名
private String myFileContentType; // MIME 類型

public void setMyFile(File file) { this.myFile = file; }
public void setMyFileFileName(String name) { this.myFileFileName = name; }
public void setMyFileContentType(String type) { this.myFileContentType = type; }

public String execute() {
    // 直接操作 myFile 物件:複製、解析、存入資料庫等
    return SUCCESS;
}

2. JSP 表單(重點:enctype="multipart/form-data" 與欄位名稱對應)

<form action="upload.action" method="post" enctype="multipart/form-data">
    <input type="file" name="myFile" />
    <input type="submit" value="上傳" />
</form>

3. xwork.xml 配置攔截器堆疊

<interceptor-stack name="fileUploadStack">
    <interceptor-ref name="fileUpload"/>
    <interceptor-ref name="basicStack"/>
</interceptor-stack>

<action name="upload" class="com.example.UploadAction">
    <interceptor-ref name="fileUploadStack"/>
    <result name="success">/success.jsp</result>
</action>

進階設定

  • maximumSize:限制上傳大小(預設 2MB),可在 webwork.properties 覆蓋。
  • allowedTypes:限制 MIME 類型。
  • 多檔上傳:Action 定義 List<File> 與對應的 List<String> 檔名/類型屬性。

採用慣例優於配置原則,WebWork 讓檔案上傳變得像處理一般表單欄位一樣簡潔。

Copyright © Windows教程網 All Rights Reserved