我希望我的 Spring Controller 缓存返回的内容。我发现了很多关于如何禁用缓存的问题。我想知道如何启用缓存。我的 Controller 看起来像这样:
@Controller
public class SimpleController {
@RequestMapping("/webpage.htm")
public ModelAndView webpage(HttpServletRequest request,
HttpServletResponse response) {
ModelAndView mav = new ModelAndView("webpage");
httpServletResponse.setHeader(“Cache-Control”, “public”);
//some code
return mav;
}
}
如您所见,我添加了以下行:httpServletResponse.setHeader(“Cache-Control”, “public”);
来设置缓存,但是在我的浏览器中,当我刷新此页面时,我仍然获得相同的状态结果:200 OK
。如何实现 304 not modified
结果?我可以在此方法上设置注释 @ResponseStatus(value = HttpStatus.NOT_MODIFIED)
但它只是状态还是实际缓存?
最佳答案
public
- Indicates that the response MAY be cached by any cache, even if it would normally be non-cacheable or cacheable only within a non- shared cache.
基本上 Cache-Control: public
是不够的,它只要求浏览器缓存正常不缓存的资源,例如通过 HTTPS。
HTTP 中的缓存实际上相当复杂,它涉及到其他几个 header :
Cache-Control
- 上面讨论过Expires
- 当给定资源应被视为过时Last-Modified
- 上次修改资源的时间ETag
- 资源的唯一标签,在每次修订中都会更改Vary
- 根据不同的header单独缓存If-Modified-Since
,If-None-Match
, ...
我找到了 Caching Tutorial相当全面。并非所有 header 都应该一起使用,您必须真正确定自己在做什么。因此,我建议使用内置解决方案,如 EhCache web caching .
同样,用如此低级的细节污染你的 Controller 也不是一个好主意。
关于java - 在 Spring MVC 应用程序中缓存 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12997517/