caching images served by servlet

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>

Leave a Comment