I have some images in my website that rarely change, but the page reload rerenders them over and over again, returning code 200 OK. I would like to cache those images so I'll get back a 304. I'm using the Spting MVC, and I have used the HttpServletResponse setHeader method.
httpResponse.setHeader("Cache-Control", "max-age=36000");
Problem is that this method sets the header to the entire response, rather than to a single image. What I would like to do is set the headers to a single file being transfered in the network, such as image. How can I achieve that?
You need to set the cache-control header to the image response, but not to the html-page response.
If you want to apply the cache-control header to all images, then springs WebContentInterceptor
will do this for you:
<mvc:interceptors>
...
<!-- explicite no caching for all response, except png-images -->
<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
<property name="alwaysUseFullPath" value="true"/>
<property name="cacheMappings">
<props>
<!-- 2678400 seconds = 31 days -->
<prop key="/resources/images/**/*.png">2678400</prop>
</props>
</property>
</bean>
</mvc:interceptors>
this solution will set max-age=2678400, but will not send a 304 response! Intead the browser will even not send a second request for this image again, because the browser will cache the image.