在搞关于Servlet的Response下载文件功能,照着视频敲了一遍,视频里getRealPath("");用的是电脑文件的绝对路径,我想自己研究研究改成相对路径,经最后研究结果,代码如下:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getServletContext().getRealPath("/");
String wholePath = path + "WEB-INF/classes/1.png";
File file = new File(wholePath);
System.out.println("file is exist :" + file.exists());
String filename = wholePath.substring(wholePath.lastIndexOf("/")+1);
resp.setHeader("Content-Disposition", "attachment; filename=" + filename);
FileInputStream fis = new FileInputStream(wholePath);
int len = 0;
byte[] buffer = new byte[1024];
ServletOutputStream out = resp.getOutputStream();
while ((len = fis.read(buffer)) > 0){
System.out.println("写进来了吗");
out.write(buffer, 0, len);
}
fis.close();
out.close();
}
遇到的坑:
1、File file = new File("");的时候,就算目录下不存在该file,也是能打印file.getPath()的,我一开始以为打印了路径就证明有这个file,too young too naive,后来换成exists()方法就正确了
2、报了个错:

我以为是HttpServlet相关的配置文件之类的配错了,或者doGet、doPost方法写错了,这顿找原因。
后来才发现是输出时while(...)循环没走就报这个错误,他竟然不报个HTTP500系的错,整个这玩意
PS1:
经过后面的学习才知道,图片不应该放到resources这个路径下面,WEB-INF下面的文件对用户是不可见的,放的应该是机密文件,正常的图片资源应该放在web主目录下,建一些static文件夹之类的。