【问题标题】:Caching an image to return code 304 rahter than 200缓存图像以返回代码 304 而不是 200
【发布时间】:2015-10-31 08:35:41
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

    如果您想将缓存控制标头应用于所有图像,那么 springs 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 浏览器甚至不会再次发送对该图像的第二次请求,因为浏览器会缓存该图像。

    【讨论】:

    • 感谢您的快速回复! Ans 如果我只想缓存一个图像怎么办?如何设置特定图像本身的响应?
    • @Anton Raskin:那么您要么需要微调密钥文件名匹配,要么需要自定义 WebContentInterceptor。另一种方法是实现一个提供图像的自定义控制器,在这个控制器中你可以发送你想要的每个标题和返回码。
    猜你喜欢
    • 2017-12-01
    • 2012-12-29
    • 1970-01-01
    • 2015-06-28
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多