用于浏览器缓存的Servlet过滤器? [英] Servlet filter for browser caching?

查看:94
本文介绍了用于浏览器缓存的Servlet过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does anyone know how to go about coding a servlet filter that will set cache headers on a response for a given file/content type? I've got an app that serves up a lot of images, and I'd like to cut down on bandwidth for hosting it by having the browser cache the ones that don't change very often. Ideally, I'd like to be able to specify a content type and have it set the appropriate headers whenever the content type matches.

有谁知道如何去做这个?或者,更好的是,他们愿意分享示例代码?谢谢!

Does anyone know how to go about doing this? Or, even better, have sample code they'd be willing to share? Thanks!

推荐答案

在你的过滤器中有这一行:

In your filter have this line:

chain.doFilter(httpRequest, new AddExpiresHeaderResponse(httpResponse));

响应包装器的位置如下:

Where the response wrapper looks like:

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

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

In short, this creates a response wrapper, which, on setting the content type, adds the expires header. (If you want, you can add whatever other headers you need as well). I've been using this filter + wrapper and it works.

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

See this question on one specific problem that this solves, and the original solution by BalusC.

这篇关于用于浏览器缓存的Servlet过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆