I'm serving up images from my servlet. The response content type is image/jpeg. I find that images requested from my servlet are not cached. How do I get them to be cached like file image requests normally are? I tried setting Cache-Control: public but to no avail.
The default servlet serving static content in containers like Tomcat doesn't set any cache control headers. You don't need write a servlet just for that. Just create a filter like this,
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
long expiry = new Date().getTime() + cacheAge*1000;
HttpServletResponse httpResponse = (HttpServletResponse)response;
httpResponse.setDateHeader("Expires", expiry);
httpResponse.setHeader("Cache-Control", "max-age="+ cacheAge);
chain.doFilter(request, response);
}
Whenever you want add cache control, just add the filter to the resources in web.xml. For example,
<filter>
<filter-name>CacheControl</filter-name>
<filter-class>filters.CacheControlFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CacheControl</filter-name>
<url-pattern>/images/*</url-pattern>
</filter-mapping>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With