這里是一個(gè)從服務(wù)器下載文件的簡(jiǎn)單例子。假設(shè)想要下載項(xiàng)目根目錄中的home.jsp
文件。如果有任何jar
或zip
文件,可以直接提供該文件的鏈接,不必編寫(xiě)程序來(lái)下載這樣的文件。 但是如果有任何java
文件或者jsp
文件等,則需要編寫(xiě)一個(gè)程序來(lái)下載這類(lèi)文件。
打開(kāi)Eclipse,創(chuàng)建一個(gè)動(dòng)態(tài)Web項(xiàng)目:ServletDownloadFile,其完整的目錄結(jié)構(gòu)如下所示 -
在這個(gè)例子中,創(chuàng)建了三個(gè)文件:
文件:index.html
該文件提供了一個(gè)下載文件的鏈接。參考下面代碼 -
<!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
這是一個(gè)實(shí)現(xiàn)servlet的文件,讀取文件的內(nèi)容并將其寫(xiě)入流中作為響應(yīng)發(fā)送給客戶(hù)端。因此需要通知服務(wù)器將內(nèi)容類(lèi)型設(shè)置為:APPLICATION/OCTET-STREAM
。
package com.yiibai;
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
此配置文件向服務(wù)器提供有關(guān)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.yiibai.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/DownloadJSP</url-pattern>
</servlet-mapping>
</web-app>
在編寫(xiě)上面代碼后,部署此Web應(yīng)用程序(在項(xiàng)目名稱(chēng)上點(diǎn)擊右鍵->”Run On Server…”),打開(kāi)瀏覽器訪問(wèn)URL: http://localhost:8080/ServletDownloadFile/ ,如果沒(méi)有錯(cuò)誤,應(yīng)該會(huì)看到以下結(jié)果 -
點(diǎn)擊上頁(yè)面中的“下載JSP文件”鏈接,可以看到以下結(jié)果 -