MaintainAction 核心邏輯,並修正原文錯誤。作為控制層入口,MaintainAction 負責:
MaintainForm 取出業務數據 (Trainplan) 與上傳文件 (FormFile)。Trainplan 附件字段,委派 TrainPlanDAO 入庫。veiwtrainplan.jsp)。package tester.business.maitain;
import tclcc.tester.util.Selector;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.util.*;
import org.apache.struts.upload.FormFile;
import java.io.*;
public class MaintainAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
MaintainForm maintainForm = (MaintainForm) form;
TrainPlanDAO trainPDAO = new TrainPlanDAO();
Trainplan trainPlan = maintainForm.getTrainPlan();
// 處理第一個上傳文件(示範單文件,多文件可循環處理)
FormFile theFile = maintainForm.getTheFile1();
String p_accessory = "";
if (theFile != null && theFile.getFileSize() > 0) {
p_accessory = theFile.getFileName();
try {
InputStream stream = theFile.getInputStream();
// 實際項目建議:配置上傳根目錄,而非 getRealPath("/")
String uploadRoot = request.getServletContext().getInitParameter("upload.root");
if (uploadRoot == null) uploadRoot = request.getRealPath("/") + "upload/";
File dir = new File(uploadRoot);
if (!dir.exists()) dir.mkdirs();
File destFile = new File(dir, p_accessory);
OutputStream bos = new FileOutputStream(destFile);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();
theFile.destroy(); // 釋放臨時文件
} catch (Exception e) {
e.printStackTrace();
// 記錄日誌、返回錯誤頁
}
}
try {
trainPlan.setP_accessory(p_accessory);
trainPDAO.addTrainPlan(trainPlan); // 入庫
System.out.println("success");
} catch (Exception ex) {
ex.printStackTrace();
// 事務回滾、錯誤處理
}
request.setAttribute("trainPlain", trainPlan); // 注意:原文拼寫 trainPlain
return mapping.findForward("trainplanCreated");
}
}
| 原文問題 | 修正建議 |
|---|---|
硬編碼路徑 filePath + "\sub\" | 使用 ServletContext.getInitParameter 或 Spring @Value 外部化配置上傳目錄 |
未調用 FormFile.destroy() | 必須在 finally 塊調用,釋放容器臨時文件 |
| 單文件處理,忽略 theFile2/3 | 封裝 handleUpload(FormFile) 方法,循環處理集合 |
| DAO 直接 new,強耦合 | 採用依賴注入(Spring @Autowired)或 ServiceLocator 獲取 DAO |
| 異常吞沒,無用戶反饋 | 捕獲異常後 ActionMessages errors = new ActionMessages(); errors.add(...); saveErrors(request, errors); return mapping.getInputForward(); |
FormFile,支援流式處理、大文件斷點續傳。理解經典 Struts 上傳流程,有助於維護舊系統;新建專案請直接採用現代技術棧。