Servlet下載檔

這裏是一個從伺服器下載檔的簡單例子。假設想要下載專案根目錄中的home.jsp檔。如果有任何jarzip檔,可以直接提供該檔的鏈接,不必編寫程式來下載這樣的檔。 但是如果有任何java檔或者jsp檔等,則需要編寫一個程式來下載這類檔。

在servlet中從伺服器下載檔的示例

打開Eclipse,創建一個動態Web專案:ServletDownloadFile,其完整的目錄結構如下所示 -

在這個例子中,創建了三個檔:

  • index.html - 首頁入口
  • DownloadServlet.java - 處理要下載的檔並向客戶端輸出檔下載。
  • web.xml - 此配置檔向伺服器提供有關servlet的資訊。

檔:index.html

該檔提供了一個下載檔的鏈接。參考下麵代碼 -

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Servlet下載檔示例</title>
</head>
<body>
<div style="margin:auto;text-align:center;">
    <a href="DownloadJSP">下載JSP檔</a>
</div>
</body>
</html>

檔:DownloadServlet.java

這是一個實現servlet的檔,讀取檔的內容並將其寫入流中作為回應發送給客戶端。因此需要通知伺服器將內容類型設置為:APPLICATION/OCTET-STREAM

package com.zaixian;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class DownloadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String filepath = request.getSession().getServletContext().getRealPath("");
        String filename = "home.jsp";
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

        FileInputStream fileInputStream = new FileInputStream(filepath + filename);

        int i = 0;
        while ((i = fileInputStream.read()) != -1) {
            out.write(i);
        }
        fileInputStream.close();
        out.close();
    }

}

檔:web.xml

此配置檔向伺服器提供有關servlet的資訊。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>ServletDownloadFile</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>DownloadServlet</servlet-name>
        <servlet-class>com.zaixian.DownloadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>DownloadServlet</servlet-name>
        <url-pattern>/DownloadJSP</url-pattern>
    </servlet-mapping>

</web-app>

在編寫上面代碼後,部署此Web應用程式(在專案名稱上點擊右鍵->”Run On Server…”),打開流覽器訪問URL: http://localhost:8080/ServletDownloadFile/ ,如果沒有錯誤,應該會看到以下結果 -

點擊上頁面中的“下載JSP檔”鏈接,可以看到以下結果 -


上一篇: Servlet上傳檔 下一篇: Servlet登錄實例