4

我有这样的 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);
   }
   ....
}

我想将标头 Last-Modified 添加到 GetUser Web 服务的 HTTP 响应中。
当缓存添加到我的商店时,如何获得正确的日期?
如何将标头 Last-Modified 与此日期一起添加到我的 Spring 控制器方法的响应中?

4

2 回答 2

15

Spring 已经内置支持处理驱动请求处理程序方法中的last-modifiedand标头。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";
}
于 2016-03-18T11:20:12.390 回答
5

这个怎么样:

@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);
    }
}
于 2014-04-11T14:54:52.913 回答