ServletContext文件下载配置学习笔记
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ServletContext文件下载配置学习笔记相关的知识,希望对你有一定的参考价值。
配置web.xml
<servlet>
<servlet-name>DownServlet01</servlet-name>
<servlet-class>cn.downservlet.DownServlet01</servlet-class>
<init-param>
<param-name>filePath</param-name>
<param-value>d:\简历.pdf</param-value>
</init-param>
</servlet>
java:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownServlet01 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// NO1
ServletConfig config = this.getServletConfig();
String filePath = config.getInitParameter("filePath");
// NO2 头信息
File file = new File(filePath);
response.setHeader("content-disposition",
"attachment;filename=" + file.getName());
// NO3
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
is.close();
os.close();
}
}
http://localhost:8080/day04/DownServlet01
以上是关于ServletContext文件下载配置学习笔记的主要内容,如果未能解决你的问题,请参考以下文章
重温Servlet学习笔记--servletContext对象
学习笔记--转Parameter与Attribute的区别&servletContext与ServletConfig区别