您的位置:首页 > 其它

idea 中 ServletContext.getRealPath 为 null

2017-08-31 20:50 1071 查看
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();

"/WEB-INF/classes/万年历.png"
最前必须加/ 否则就会返回null
而eclipse中则不用


String path = context.getRealPath("/WEB-INF/classes/万年历.png");//
String realPath = context.getRealPath("/WEB-INF/万年历.png");
System.out.println("path--" + path);
System.out.println("realPath--" + realPath);
//严重: Servlet.service() for servlet [servlet_5] in context with path [/servletTest] threw exception
//java.lang.NullPointerException
if (path != null) {
FileInputStream fis = new FileInputStream(path);
ServletOutputStream sos = response.getOutputStream();
String fileName = path.substring(path.lastIndexOf("\\") + 1);
//编码fileName
fileName = URLEncoder.encode(fileName, "utf-8");
//告知浏览器去下载 头信息
response.setHeader("content-disposition", "attachment;filename" + fileName);//文件名
response.setHeader("contetn-type", "image/png");//文件类型
byte[] b = new byte[1024];
int len;
while ((len = fis.read()) != -1) {
sos.write(b, 0, len);
}
sos.close();
} else
System.out.println("path is null");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐