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

Struts 文件上傳實戰(六):MaintainAction 核心業務邏輯

     編輯:Java 相關知識

MaintainAction.java 完整代碼

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 = theFile.getFileName();

        try {
            InputStream stream = theFile.getInputStream();
            String filePath = request.getRealPath("/");
            OutputStream bos = new FileOutputStream(filePath + "\\sub\\" + theFile.getFileName());
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            bos.close();
            stream.close();
        } catch (Exception e) { System.err.print(e); }

        try {
            trainPlan.setP_accessory(p_accessory);
            trainPDAO.addTrainPlan(trainPlan);
            System.out.println("success");
        } catch (Exception ex) {}

        request.setAttribute("trainPlain", trainPlan);
        return mapping.findForward("trainplanCreated");
    }
}

流程解析

  1. 從 MaintainForm 取得 Trainplan 與上傳檔案 FormFile。
  2. 讀取檔案輸入流,寫入伺服器磁盤 {contextRoot}/sub/{filename}。
  3. 設定附件檔名至 Trainplan,調用 DAO 入庫。
  4. 將 Trainplan 放入 Request 屬性 trainPlain,轉向 trainplanCreated(對應 veiwtrainplan.jsp)。

注意事項

  • 路徑分隔符在 Windows 下使用 \\,跨平台建議用 File.separator。
  • 缺乏檔案類型、大小驗證,生產環境需加強。
  • 異常吞沒(catch {})會隱藏錯誤,建議記錄日誌並返回錯誤頁。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved