1. 程式人生 > 其它 >JavaWeb開發常用元件功能

JavaWeb開發常用元件功能

常用元件化Web開發內容

1.檔案的上傳

(1)需要引入的 jar 檔案:commons-fileupload-1.3.2、commons-io-2.5.jar。

<!-- 檔案上傳相關包:commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

<!-- 檔案IO相關包:commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

(2)進行配置項的封裝

#-- 配置引數封裝成為成員變數
    //1.檔案上傳儲存在伺服器地址的路徑
    private static final String UPLOAD_DIRECTORY = "D:\\uploadFiles";

    // # 臨時記憶儲存大小(單位位元組)
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;
    //# 最大檔案大小(單位位元組)
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40;
    //# 最大請求大小(單位位元組)
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50;

(3) 編寫檔案上傳doPost方法

注意:檔案上傳請求只能使用post請求

3.1 判斷請求是否是包含了媒體元素上傳的請求
//1.檢測是否為檔案媒體元素上傳
        boolean multipartContent = ServletFileUpload.isMultipartContent(req);
        if(!multipartContent){//不是包含了檔案媒體元素上傳的請求

            Result res = new Result();
            res.setCode("9999");
            res.setMsg("不是一個標準的檔案上傳請求");
            writer.print(res.toString());
            writer.flush();
            writer.close();

            return;
        }
3.2 通過工廠類來生產檔案上傳物件(載入配置過程)
//2.建立工廠類
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //設定臨界值
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        //設定臨時儲存的地址
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        //生成ServletFileUpload物件
        ServletFileUpload upload = new ServletFileUpload(factory);
3.3 檔案上傳物件配置載入
// 設定最大檔案上傳值
        upload.setFileSizeMax(MAX_FILE_SIZE);
        // 設定最大請求值 (包含檔案和表單資料)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        //檔案內容編解碼字符集設定
        upload.setHeaderEncoding("UTF-8");
3.4 獲取上傳的檔案進行檔案的寫出
//1.獲取所有請求提交的元素內容
int uploadCont = 0;//檔案上傳總數計數
        try {
            List<FileItem> fileItems = upload.parseRequest(req);

            //判斷請求提交是否有內容
            if(fileItems != null&&fileItems.size()>0){//如果有內容在進行上傳檔案

                for(FileItem item : fileItems){//遍歷請求專案
                    if (!item.isFormField()){//當表單專案內容不是一個普通表單時(就是檔案)

                        //獲取上傳的檔案封裝為物件
                        System.out.println("上傳中:檔名:"+item.getName());
                        File file = new File(item.getName());

                        //封裝檔案輸出路徑和物件
                        String outPath = UPLOAD_DIRECTORY+"\\"+file.getName();
                        //封裝一個輸出的檔案物件
                        File outFile = new File(outPath);
                        //呼叫輸出方法寫出到硬碟位置
                        item.write(outFile);

                        uploadCont++;
                    }
                }

            }

        } catch (Exception e) {
            System.err.println("檔案上傳出錯");
            e.printStackTrace();
            res.setCode("9999");
            res.setMsg("檔案上傳出錯");
            writer.print(res.toString());
            writer.flush();
            writer.close();
            return;
        }

        res.setCode("0000");
        res.setMsg("檔案上傳成功!");
        res.setData(uploadCont);


        writer.print(res.toString());
        writer.flush();
        writer.close();

(4)前端檔案上傳方法

4.1 表單提交方法
<form action="http://localhost:8090/webDemo/uploadFiles"
  method="post"     #----  有檔案上傳的請求只能為post請求
      enctype="multipart/form-data"    #--- 檔案上傳必須要定義
>
    <input type="text" name="name" />
   <input type="file" name="uploadFile" />
    <input type="file" name="uploadFile2" />
   <input type="submit" value="上傳" />
</form>
4.2 ajax檔案上傳方法
<form id="myForm">
    <input type="file" name="file1"  />
    <input type="file" name="file2"  />
</form>

<button type="button" onclick="toUp()">AJAX檔案上傳</button>
function toUp(){

       //模擬一個表單資料
       console.dir($("#myForm"));
       var formData = new FormData($("#myForm")[0]);

       $.ajax({
           url:"http://localhost:8090/webDemo/uploadFiles",
           type:"POST",
           data:formData,
           async:false,
           dataType:"JSON",
           cache:false,
           contentType:false,
           processData:false,
           success:function(data){
               console.dir(data);
           },
           error:function(XMLHttpRequest, textStatus, errorThrown){
               console.dir("請求失敗!");
           }
       });
   }

(5) 專案開發中的檔案上傳管理

要求:

單個業務資料能關聯相關的檔案資訊

要設計檔案與資料關聯的中間表

實現:

能查詢資料關聯的檔案

(1)設計資料與檔案對應關係表
drop table if exists t_files;

/*==============================================================*/
/* Table: t_files                                               */
/*==============================================================*/
create table t_files
(
   isDelete             int comment '是否刪除:1:刪除 0:沒刪除',
   ipaddress            varchar(50) comment '操作者IP地址',
   addTime              datetime comment '新增時間',
   updateTime           datetime comment '修改時間',
   deleteTime           datetime comment '刪除時間',
   fileID               varchar(50) not null comment '檔案id',
   bisID                varchar(50) comment '關聯業務id',
   filePath             varchar(300) comment '檔案位置',
   fileName             varchar(50) comment '檔名稱',
   fileExt              varchar(50) comment '檔案字尾',
   fileSize             varchar(50) comment '檔案大小',
   primary key (fileID)
);

(2) 在檔案上傳時儲存資料,改寫檔名稱
 for(FileItem item : fileItems){//遍歷請求專案
                    if (!item.isFormField()){//當表單專案內容不是一個普通表單時(就是檔案)



                        //獲取上傳的檔案封裝為物件
                        System.out.println("上傳中:檔名:"+item.getName());
                        File file = new File(item.getName());

                        //檔案字尾
                        String fileName = item.getName();
                        int i = fileName.lastIndexOf(".");

                        String etx = item.getName().substring(i, item.getName().length());

                        //生成一個UUID的檔名(同時為關聯表主鍵欄位)
                        String pk = UUID.randomUUID().toString().replaceAll("-","").substring(0,20);

                        //封裝檔案輸出路徑和物件
                        String outPath = UPLOAD_DIRECTORY+"\\"+pk+etx;

                        //呼叫儲存檔案資訊到檔案關聯表中    !!!!關鍵!!!!!
                        saveFileData(item,etx,pk,"user1",outPath);//模擬一個業務id為user1

                        //封裝一個輸出的檔案物件
                        File outFile = new File(outPath);
                        //呼叫輸出方法寫出到硬碟位置
                        item.write(outFile);


                        uploadCont++;
                    }
                }
//儲存關聯資訊方法
/**
     * 儲存業務資訊與檔案資訊關聯表
     * @param item  檔案物件
     * @param etx  檔案字尾
     * @param pk  檔名稱
     * @param user1 關聯業務id
     * @param outPath  檔案儲存位置
     */
    private void saveFileData(FileItem item,String etx, String pk, String user1,String outPath) {

        Connection con = MyC3P0Util.getCon();




        String sql = "INSERT INTO `t_files` VALUES\n" +
                "\t( 0, NULL, NULL, NULL, NULL, ?, ?, ?, ?, ?, ? );";
        try{
            PreparedStatement ps = con.prepareStatement(sql);

            ps.setString(1,pk);
            ps.setString(2,user1);
            ps.setString(3,outPath);
            ps.setString(4,pk);
            ps.setString(5,etx);
            ps.setString(6,item.getSize()+"");

            ps.executeUpdate();

            con.close();
        }catch (SQLException e){
            System.err.println("儲存資料到檔案表異常!");
            e.printStackTrace();
        }


    }

2.檔案下載

3.Excel匯入

4.Excel匯出

5.Java郵件傳送

6.Tomcat的打包部署