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

Struts 文件上傳實戰 (二):ActionForm 封裝表單與上傳文件

     編輯:Java 程式設計入門

ActionForm 核心職責

MaintainForm 承擔雙重角色:

  1. 業務數據載體:組合 Trainplan 實體,透過委派模式暴露其屬性(getP_title() → trainPlan.getP_title()),實現表單字段與領域對象的無縫綁定。
  2. 文件上傳接收器:定義 3 個 org.apache.struts.upload.FormFile 屬性 (theFile1/2/3),對應 JSP <html:file> 控件。

完整代碼解析

package tester.business.maitain;

import org.apache.struts.action.*;
import javax.servlet.http.*;
import org.apache.struts.upload.*;

public class MaintainForm extends ActionForm {
    // 業務實體組合
    private Trainplan trainPlan = new Trainplan();

    // 上傳文件屬性(最多 3 個附件)
    private FormFile theFile1;
    private FormFile theFile2;
    private FormFile theFile3;

    // ---- 業務屬性委派 ----
    public String getP_title() { return trainPlan.getP_title(); }
    public void setP_title(String p_title) { trainPlan.setP_title(p_title); }
    public Trainplan getTrainPlan() { return trainPlan; }
    public void setTrainPlan(Trainplan trainPlan) { this.trainPlan = trainPlan; }

    // ---- 文件屬性 Getter/Setter ----
    public FormFile getTheFile1() { return theFile1; }
    public void setTheFile1(FormFile theFile1) { this.theFile1 = theFile1; }
    public FormFile getTheFile2() { return theFile2; }
    public void setTheFile2(FormFile theFile2) { this.theFile2 = theFile2; }
    public FormFile getTheFile3() { return theFile3; }
    public void setTheFile3(FormFile theFile3) { this.theFile3 = theFile3; }

    // ---- 生命周期鉤子 ----
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        // TODO: 實現業務驗證(標題非空、文件大小/類型限制等)
        return null;
    }

    public void reset(ActionMapping mapping, HttpServletRequest request) {
        // 重置表單狀態(如清空文件引用),防止雙擊提交殘留數據
        this.theFile1 = this.theFile2 = this.theFile3 = null;
    }
}

關鍵設計模式與最佳實踐

1. 組合優於繼承

Form 不繼承 Trainplan,而是組合它。優勢:

  • 實體類保持純粹(無框架依賴),可復用於 Service、DAO、批次任務等非 Web 場景。
  • Form 可彈性組合多個實體、添加純 UI 輔助字段(如確認密碼、驗證碼),不汙染領域模型。

2. FormFile 處理要點

  • FormFile 提供 getFileName()、getContentType()、getFileSize()、getInputStream()、destroy()(釋放臨時文件)。
  • 必須在 Action 中調用 destroy(),否則臨時文件積壓導致磁盤耗盡。

3. 驗證與重置

  • validate():返回 ActionErrors 非空時,Struts 自動轉回 input 頁面並顯示 <html:errors/>。
  • reset():在 validate() 前調用,清理上一次請求的殘留數據(特別是文件流引用)。

常見坑點排查表

現象原因解決
FormFile 為 nullJSP <html:form> 缺少 enctype="multipart/form-data"表單必須聲明 enctype="multipart/form-data"
中文文件名亂碼Tomcat 8+ 需配置 URIEncoding="UTF-8",或手動 new String(name.getBytes("ISO-8859-1"), "UTF-8")統一容器與應用編碼為 UTF-8
大文件上傳失敗超過 struts.multipart.maxSize 或容器 maxPostSize調整 struts-config.xml <controller> 與 server.xml 限制

掌握 ActionForm 的組合設計與 FormFile 生命周期管理,是構建穩健文件上傳功能的關鍵。

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