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

Struts 文件上傳實戰 (三):Action 處理上傳邏輯與業務委派

     編輯:Java 程式設計入門

注意:原文標題標註為「第三個類 action」,但代碼內容與第 2 篇 MaintainForm 完全重複。本文將補充缺失的 MaintainAction 核心邏輯,並修正原文錯誤。

MaintainAction 核心職責

作為控制層入口,MaintainAction 負責:

  1. 從 MaintainForm 取出業務數據 (Trainplan) 與上傳文件 (FormFile)。
  2. 將文件寫入服務器磁盤(或雲存儲),獲取存儲路徑/文件名。
  3. 更新 Trainplan 附件字段,委派 TrainPlanDAO 入庫。
  4. 設置請求屬性,轉發至結果頁 (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();

現代化重構方向

  • Spring MVC + MultipartFile:替代 Struts FormFile,支援流式處理、大文件斷點續傳。
  • 服務層封裝:Action → Service (事務邊界) → DAO/Repository,Action 僅做參數轉換與視圖跳轉。
  • 雲存儲整合:上傳至 S3/OSS/MinIO,資料庫存 Object Key,消除應用服務器有狀態依賴。
  • 異步上傳:前端直傳對象存儲,回調業務 API 保存元數據,釋放 Web 線程。

理解經典 Struts 上傳流程,有助於維護舊系統;新建專案請直接採用現代技術棧。

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