我有这样的Spring MVC控制器:
@Controller
@RequestMapping(value = "/user")
public class UserController {
.....
@Cacheable(value = "users", key = "#id")
@RequestMapping(value = "/get", method = RequestMethod.GET)
@ResponseBody
public User getUser(Long id){
return userService.get(id);
}
....
}我想添加标头最后修改到GetUser网络服务的超文本传输协议响应。
当缓存被添加到我的商店时,我如何获得正确的日期?
如何将带有此日期的Last-Modified头文件添加到Spring控制器方法的响应中?
发布于 2014-04-11 22:54:53
这样如何:
@Controller
@RequestMapping(value = "/user")
class UserController {
@Cacheable(value = "users", key = "#id")
@RequestMapping(value = "/get", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<User> getUser(Long id) {
HttpHeaders headers = new HttpHeaders();
headers.set("Last-Modified", dateFormat.format(new Date()));
return new ResponseEntity<SecurityProperties.User>(headers, userService.get(id), HttpStatus.OK);
}
}发布于 2016-03-18 19:20:12
Spring已经有一个内置的支持来处理for驱动请求处理器方法中的last-modified和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";
}https://stackoverflow.com/questions/23014803
复制相似问题