2

我正在使用<enable-file-serving value="true" />WebSphere Application Server v7.0 的特性为我的 Java Web 应用程序提供静态内容(图像、CSS、JavaScript)。

如何修改此静态内容的 HTTP 标头(例如,添加一个Cache-ControlExpires标头)?

4

1 回答 1

3

我最终编写了一个Filter基于所请求资源的 URL 添加 HTTP 标头。这是一个简化版本:

CacheFilter.java

public class CacheFilter implements Filter {
    private static long maxAge = 86400 * 30; // 30 days in seconds

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Cache-Control", "max-age=" + maxAge);
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}

web.xml

<filter>
    <filter-name>cache</filter-name>
    <filter-class>com.example.CacheFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cache</filter-name>
    <url-pattern>*.png</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>cache</filter-name>
    <url-pattern>*.jpg</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>cache</filter-name>
    <url-pattern>*.gif</url-pattern>
</filter-mapping>
于 2013-03-12T15:54:01.403 回答