(moved from the duplicate question)
Add a filter (javax.servlet.Filter
) that adds the cache headers whenever the response contains an image. Something like:
public class StaticResourceCacheFilter implements Filter {
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 void init(FilterConfig cfg) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
chain.doFilter(httpRequest, httpResponse);
String contentType = httpResponse.getContentType();
if (contentType != null && Arrays.binarySearch(CACHEABLE_CONTENT_TYPES, contentType) > -1) {
Calendar inTwoMonths = Calendar.getInstance();
inTwoMonths.add(Calendar.MONTH, 2);
httpResponse.setHeader("Expires", DateUtil.formatDate(inTwoMonths.getTime()));
} else {
httpResponse.setHeader("Expires", "-1");
}
}
(where DateUtil
is org.apache.commons.httpclient.util.DateUtil
)
The above filter, of course, assumes you have set the right Content-Type
for your images. Otherwise I think they might not be displayed properly in the browser, with or without cache.
To answer your question:
Is there any way to keep the images in cache until the image get modified in server.
That's a different scenario. You can store your images in some cache implementation (ehcache for example), but this is a server cache, not client cache.