码迷,mamicode.com
首页 > 其他好文 > 详细

servlet设置缓存时间以及文件的下载

时间:2015-08-19 12:37:40      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

缓存时间的设置:

1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2             throws ServletException, IOException {
3 
4         response.setContentType("text/html;charset=UTF-8");
5         PrintWriter out = response.getWriter();
6         response.setDateHeader("Expires", System.currentTimeMillis()+60*60*1000);//缓存时间一小时
7         out.write("hello world");
8 }

 

通知客户端文件的下载,此处以图片为例:

 1     public void doGet(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         response.setContentType("text/html");
 4         ServletContext context=getServletContext();
 5         
 6         String path=context.getRealPath("/picture.jpg");
 7         String fileName=path.substring(path.lastIndexOf("\\")+1);
 8         InputStream in=new FileInputStream(path);
 9         
10         //通知客户端文件的下载    URLEncoder.encode解决文件名中文的问题
11         response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
12         response.setHeader("Content-Type", "application/octet-stream");
13         
14         OutputStream out=response.getOutputStream();
15         int length=-1;
16         byte []buffer=new byte[1024];
17         while((length=in.read(buffer))!=-1){
18             out.write(buffer,0,length);
19         }
20         in.close();
21     }

 

servlet设置缓存时间以及文件的下载

标签:

原文地址:http://www.cnblogs.com/z941030/p/4741616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!