I'm using the <enable-file-serving value="true" />
feature of WebSphere Application Server v7.0 to serve static content (images, CSS, JavaScripts) for my Java web app.
How can I modify the HTTP headers for this static content (e.g., add a Cache-Control
or Expires
header)?
I ended up writing a Filter
to add the HTTP header based on the URL of the requested resource. Here's a simplified version:
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>