首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为使用Spring Cache缓存的Spring Web服务设置正确的Last-Modified header值?

如何为使用Spring Cache缓存的Spring Web服务设置正确的Last-Modified header值?
EN

Stack Overflow用户
提问于 2014-04-11 22:00:40
回答 2查看 10.1K关注 0票数 4

我有这样的Spring MVC控制器:

代码语言:javascript
复制
@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控制器方法的响应中?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-11 22:54:53

这样如何:

代码语言:javascript
复制
@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);
    }
}
票数 5
EN

Stack Overflow用户

发布于 2016-03-18 19:20:12

Spring已经有一个内置的支持来处理for驱动请求处理器方法中的last-modifiedIf-Modified-Since头。

它是基于WebRequest.checkNotModified(long lastModifiedTimestamp)

这个例子取自java文档:

这也将透明地设置适当的响应头,无论是已修改的案例还是未修改的案例。典型用法:

代码语言:javascript
复制
 @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完成后调用的内部方法上。

代码语言:javascript
复制
 //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";
}
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23014803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档