Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

caching images served by servlet

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.

like image 893
akula1001 Avatar asked May 20 '10 09:05

akula1001


1 Answers

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>
like image 100
ZZ Coder Avatar answered Oct 27 '22 00:10

ZZ Coder