Spring 已经内置支持处理驱动请求处理程序方法中的last-modified
and标头。If-Modified-Since
它基于WebRequest.checkNotModified(long lastModifiedTimestamp)
此示例仅取自 java 文档:
这也将透明地设置适当的响应标头,用于修改的情况和未修改的情况。典型用法:
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String myHandleMethod(WebRequest webRequest, Model model) {
long lastModified = // application-specific calculation
if (request.checkNotModified(lastModified)) {
// shortcut exit - no further processing necessary
return null;
}
// further request processing, actually building content
model.addAttribute(...);
return "myViewName";
}
但是您的@Cacheable
注释是一个问题,因为它会阻止执行该方法(对于第二次调用),因此request.checkNotModified
不会调用该方法。- 如果缓存很重要,那么您可以@Cacheable
从控制器方法中删除注释并将其放在request.checkNotModified
完成后调用的内部方法上。
//use selfe in order to use annotation driven advices
@Autowire
YourController selfe;
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String myHandleMethod(WebRequest webRequest, Model model) {
long lastModified = // application-specific calculation
if (request.checkNotModified(lastModified)) {
// shortcut exit - no further processing necessary
return null;
} else {
return selfe.innerMyHandleMethod(model);
}
}
@Cacheable(value = "users", key = "#id")
public String innerMyHandleMethod(Model model) {
model.addAttribute(...);
return "myViewName";
}