我正在使用WebSphere Application Server v7.0的<enable-file-serving value="true" />
功能为我的Java Web应用程序提供静态内容(图像,CSS,JavaScripts)。
如何修改此静态内容的HTTP标头(例如,添加Cache-Control
或Expires
标头)?
答案 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>