繁体   English   中英

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

[英]Servlet filter for browser caching?

有谁知道如何编写一个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);
    }
}

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

有关此问题的一个特定问题以及BalusC的原始解决方案, 请参阅此问题

以下是此https://github.com/samaxes/javaee-cache-filter的现成解决方案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM