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

缓存时间的设置:

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        response.setDateHeader("Expires", System.currentTimeMillis()+60*60*1000);//缓存时间一小时
        out.write("hello world");
}

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

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        ServletContext context=getServletContext();

        String path=context.getRealPath("/picture.jpg");
        String fileName=path.substring(path.lastIndexOf("\\")+1);
        InputStream in=new FileInputStream(path);

        //通知客户端文件的下载    URLEncoder.encode解决文件名中文的问题
        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
        response.setHeader("Content-Type", "application/octet-stream");

        OutputStream out=response.getOutputStream();
        int length=-1;
        byte []buffer=new byte[1024];
        while((length=in.read(buffer))!=-1){
            out.write(buffer,0,length);
        }
        in.close();
    }

博客园博客:欠扁的小篮子

坚持原创技术分享,您的支持将鼓励我继续创作!
0%