有谁知道如何编写一个 servlet 过滤器来为给定文件/内容类型的响应设置缓存 header ?我有一个提供大量图像的应用程序,我想通过让浏览器缓存不经常更改的图像来减少托管它的带宽。理想情况下,我希望能够指定内容类型,并在内容类型匹配时设置适当的 header 。
有人知道怎么做吗?或者,更好的是,有他们愿意分享的示例代码?谢谢!
最佳答案
在你的过滤器中有这一行:
chain.doFilter(httpRequest, new AddExpiresHeaderResponse(httpResponse));
响应包装器的样子:
class AddExpiresHeaderResponse extends HttpServletResponseWrapper {
public static final String[] CACHEABLE_CONTENT_TYPES = new String[] {
"text/css", "text/javascript", "image/png", "image/jpeg",
"image/gif", "image/jpg" };
static {
Arrays.sort(CACHEABLE_CONTENT_TYPES);
}
public AddExpiresHeaderResponse(HttpServletResponse response) {
super(response);
}
@Override
public void setContentType(String contentType) {
if (contentType != null && Arrays.binarySearch(CACHEABLE_CONTENT_TYPES, contentType) > -1) {
Calendar inTwoMonths = GeneralUtils.createCalendar();
inTwoMonths.add(Calendar.MONTH, 2);
super.setDateHeader("Expires", inTwoMonths.getTimeInMillis());
} else {
super.setHeader("Expires", "-1");
super.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
}
super.setContentType(contentType);
}
}
简而言之,这会创建一个响应包装器,它在设置内容类型时添加过期 header 。 (如果你愿意,你也可以添加你需要的任何其他标题)。我一直在使用这个过滤器 + 包装器并且它有效。
See this question关于这解决的一个特定问题,以及 BalusC 的原始解决方案。
关于java - 用于浏览器缓存的 Servlet 过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3374703/