WebSphere 7:修改静态内容文件服务的HTTP标头

时间:2013-03-12 14:26:11

标签: caching http-headers websphere servlet-filters websphere-7

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

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

1 个答案:

答案 0 :(得分: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>