在基于注解的Spring MVC控制器中,为特定路径设置缓存头的首选方法是什么?
发布于 2009-09-01 18:00:38
org.springframework.web.servlet.support.WebContentGenerator是所有Spring控制器的基类,它有相当多的方法处理缓存头:
/* Set whether to use the HTTP 1.1 cache-control header. Default is "true".
* <p>Note: Cache headers will only get applied if caching is enabled
* (or explicitly prevented) for the current request. */
public final void setUseCacheControlHeader();
/* Return whether the HTTP 1.1 cache-control header is used. */
public final boolean isUseCacheControlHeader();
/* Set whether to use the HTTP 1.1 cache-control header value "no-store"
* when preventing caching. Default is "true". */
public final void setUseCacheControlNoStore(boolean useCacheControlNoStore);
/* Cache content for the given number of seconds. Default is -1,
* indicating no generation of cache-related headers.
* Only if this is set to 0 (no cache) or a positive value (cache for
* this many seconds) will this class generate cache headers.
* The headers can be overwritten by subclasses, before content is generated. */
public final void setCacheSeconds(int seconds);它们既可以在内容生成之前在控制器中调用,也可以在Spring上下文中指定为bean属性。
发布于 2010-10-14 07:49:14
我只是遇到了同样的问题,并且找到了框架已经提供的一个很好的解决方案。org.springframework.web.servlet.mvc.WebContentInterceptor类允许您定义默认缓存行为,以及特定于路径的覆盖(具有其他地方使用的相同路径匹配器行为)。我要做的步骤是:
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter实例未设置"cacheSeconds“属性。WebContentInterceptor的实例:... 2592000 -1
在这些更改之后,缓存下的响应包括不鼓励缓存的标头,/ /foo /me下的响应包括鼓励缓存的标头,/cache/agnostic下的响应不包括与缓存相关的标头。
如果使用纯Java配置:
@EnableWebMvc
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
/* Time, in seconds, to have the browser cache static resources (one week). */
private static final int BROWSER_CACHE_CONTROL = 604800;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/images/**")
.addResourceLocations("/images/")
.setCachePeriod(BROWSER_CACHE_CONTROL);
}
}另请参阅:http://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html
发布于 2010-02-25 20:37:41
答案很简单:
@Controller
public class EmployeeController {
@RequestMapping(value = "/find/employer/{employerId}", method = RequestMethod.GET)
public List getEmployees(@PathVariable("employerId") Long employerId, final HttpServletResponse response) {
response.setHeader("Cache-Control", "no-cache");
return employeeService.findEmployeesForEmployer(employerId);
}
}上面的代码准确地显示了您想要实现的目标。你必须做两件事。添加"final HttpServletResponse response“作为参数。然后将header Cache-Control设置为no-cache。
https://stackoverflow.com/questions/1362930
复制相似问题