java,缓存图像不起作用,尽管响应头有max-age

时间:2016-02-11 10:57:06

标签: java caching filter

看来这是缓存的:

  

http://agrozoo.net/UploadedImages/d334e86792a547389580a5b5a6a9dcf2_thumb.jpg

而这不是:

  

http://agrozoo.net/UploadedImages/d334e86792a547389580a5b5a6a9dcf2-Phlebia-livida.jpg

从firefox / firebug拍摄的示例屏幕,左缓存,右缓存

在第一种情况下我做的很简单:

chain.doFilter(request, response);

第二名:

response.setContentType("image/jpg");
            OutputStream os = response.getOutputStream();
            ImageIO.write(buffer, "jpg", os);
            os.close();

如何使其在第二种情况下缓存?

2 个答案:

答案 0 :(得分:0)

左侧和右侧都有Cache-Control: max-age=0标头,将禁用缓存

但左边有一个etag可能会导致缓存

请参阅here以查看可禁用缓存的标头

答案 1 :(得分:0)

解决方案:

response.setHeader("ETag", eTag);



if (request.getHeader("If-None-Match") != null && request.getHeader("If-None-Match").equals(eTag))
{        
  response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); // 304
  response.setContentType("image/jpg");
  OutputStream os = response.getOutputStream();
  buffer.flush();//force 0 B jpg image, don't need to send anything as it will be pulled from browser cache
  ImageIO.write(buffer, "jpg", os);
  os.close();
}
else
{    

response.setContentType("image/jpg");
OutputStream os = response.getOutputStream();
ImageIO.write(buffer, "jpg", os);
os.close();
}