缓存图像以返回超过200的代码304

时间:2015-10-31 08:35:41

标签: spring http spring-mvc http-headers request-headers

我的网站上有一些很少更改的图片,但页面重新加载会一遍又一遍地重新呈现它们,返回代码200 OK。我想缓存这些图像,以便我回到304。 我使用Spting MVC,并且我使用了HttpServletResponse setHeader方法。

    httpResponse.setHeader("Cache-Control", "max-age=36000"); 

问题是此方法将标题设置为整个响应,而不是单个图像。我想要做的是将标题设置为在网络中传输的单个文件,例如图像。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

您需要将缓存控制标头设置为图像响应,而不是html页面响应。

如果要将缓存控制标头应用于所有图像,则弹簧WebContentInterceptor将为您执行此操作:

<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>

此解决方案将设置max-age = 2678400,但不会发送304响应! Intead浏览器甚至不会再次发送此图像的第二个请求,因为浏览器将缓存图像。