1. 程式人生 > 其它 >叢集搭建系列(十五) 叢集除錯常用命令

叢集搭建系列(十五) 叢集除錯常用命令

什麼是HttpSevletResponse

web伺服器接收到客戶端的http請求,針對這個請求,分別建立一個代表請求的HttpServletRequest物件,代表響應的一個HttpServletResponse

案例:下載檔案

下載檔案思路:

  • 下載檔案路徑
  • 下載檔名稱
  • 瀏覽器支援下載格式
  • 獲取下載檔案的輸入流
  • 建立緩衝區
  • 獲取OutputStream物件
  • 將FileOutStream流寫入到buffer緩衝區
  • OutputStream將緩衝區資料輸出到客戶端
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1. 下載檔案路徑
    String realPath = "xxxx";
    System.out.println("下載檔案的路徑:"+realPath);
    // 2. 下載檔名稱
    String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
    // 3. 瀏覽器支援下載格式
    resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
    // 4. 獲取下載檔案的輸入流
    FileInputStream in = new FileInputStream(realPath);
    // 5. 建立緩衝區
    int len = 0;
    byte[] buffer = new byte[1024];
    // 6. 獲取OutputStream物件
    ServletOutputStream out = resp.getOutputStream();
    // 7. 將FileOutputStream流寫入到buffer緩衝區,使用OutputStream將緩衝區中的資料輸出到客戶端!
    while ((len=in.read(buffer))>0){
        out.write(buffer,0,len);
    }

    in.close();
    out.close();
}