MaintainForm 承擔雙重角色:
Trainplan 實體,透過委派模式暴露其屬性(getP_title() → trainPlan.getP_title()),實現表單字段與領域對象的無縫綁定。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;
}
}
Form 不繼承 Trainplan,而是組合它。優勢:
FormFile 提供 getFileName()、getContentType()、getFileSize()、getInputStream()、destroy()(釋放臨時文件)。destroy(),否則臨時文件積壓導致磁盤耗盡。validate():返回 ActionErrors 非空時,Struts 自動轉回 input 頁面並顯示 <html:errors/>。reset():在 validate() 前調用,清理上一次請求的殘留數據(特別是文件流引用)。| 現象 | 原因 | 解決 |
|---|---|---|
| FormFile 為 null | JSP <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 生命周期管理,是構建穩健文件上傳功能的關鍵。