用于浏览器缓存的Servlet过滤器?


问题内容

有谁知道如何编写一个servlet过滤器,该过滤器将在给定文件/内容类型的响应上设置缓存头?我有一个提供大量图像的应用程序,我想通过让浏览器缓存那些不经常更改的图像来减少托管它的带宽。理想情况下,我希望能够指定一种内容类型,并在内容类型匹配时让它设置适当的标题。

有人知道该怎么做吗?或者,甚至更好的是,他们愿意共享示例代码吗?谢谢!


问题答案:

在您的过滤器中有以下行:

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);
    }
}

简而言之,这将创建一个响应包装,该包装在设置内容类型时会添加expires标头。(如果需要,还可以添加所需的其他任何标题)。我一直在使用这个过滤器+包装器,并且可以正常工作。

有关解决的一个特定问题和BalusC的原始解决方案,请参见此问题。