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

9/6/2015来源:Java教程人气:1746

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

缓存时间的设置:

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     }