开发者

how to set header no cache in spring mvc 3 by annotation

开发者 https://www.devze.com 2023-01-29 14:31 出处:网络
how to set h开发者_开发问答eader no cache in spring mvc 3 by annotation? not is response.setHeader(\"Pragma\",\"No-cache\");

how to set h开发者_开发问答eader no cache in spring mvc 3 by annotation? not is

  response.setHeader("Pragma","No-cache");     
  response.setHeader("Cache-Control","no-cache");     
  response.setDateHeader("Expires",   0);     


There is no such option. You can use an interceptor:

<mvc:annotation-driven/>
<mvc:interceptors>
    <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"/>
    </bean>
</mvc:interceptors>

(taken from here)

On one hand it is logical not to have such annotation. Annotations on spring-mvc methods are primarily to let the container decide which method to invoke (limiting it by a request header, request url, or method). Controlling the response does not fall into this category.

On the other hand - yes, it will be handy to have these, because when controllers are unit-tested it is not relevant to test http header stuff (or is it?). And there are @ResponseBody and @ResponseStatus, which do specify some response properties.


To override the settings for certain controller mappings use the cacheMappings properties object on the WebContentInterceptor

<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="2100" />
<property name="useExpiresHeader" value="true" />
<property name="useCacheControlHeader" value="true" />
<property name="useCacheControlNoStore" value="true" />
<property name="cacheMappings">
    <props>
        <prop key="/myUncachedController">0</prop>
    </props>
</property>


I know this is old but this might be helpful to some.

If you wanted to add a lot more logic to when you cache and when you don't you can also write a custom interceptor.

For example if you wanted to disable caching in the response only when the browser is IE or only from specific urls you can do that as well by extending the HandlerInterceptor interface.

By doing that you can have a lot of control over exactly what happens. It's not as easy as just setting the header for everything at once or just typing in the changes to the response in each controller but it is also not that hard and is a better long term solution in my opinion. It is also a good thing to know how to do in spring generally.

This is a pretty good tutorial for it:

http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/

0

精彩评论

暂无评论...
验证码 换一张
取 消