【问题标题】:Spring controller doesn't get Cache Control headerSpring控制器没有获得缓存控制头
【发布时间】:2017-10-30 16:26:45
【问题描述】:

我想在响应的缓存控制标头中设置最大年龄。我已经写了如下,但仍然有 max-age 0。我只想为一种方法设置最大年龄,所以我不想禁用默认值。我认为应该是 ovveride。

 @ApiOperation(value = "get value by foreign currency", response = Property.class)
@RequestMapping(method = RequestMethod.GET, value = "/properties/{id}")
@ResponseBody
public ResponseEntity<BigDecimal> getValueByForeignCurrency(@PathVariable Long id,
                                                @RequestParam("currency") String currency, Locale locale) {
    if (!ForeignCurrency.isLegalCurrency(currency)) {
        throw new IllegalArgumentException("Currency: " + currency + " is not legal");
    }

    BigDecimal foreignValue = propertyService.getPropertyValueInForeignCurrency(id, currency, locale);

    return ResponseEntity.ok().cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS))
            .body(foreignValue);
}

有人知道我做错了什么吗?

【问题讨论】:

  • SpringSecurity,默认设置为no-cache 模式。您可以在HttpServletResponse 对象中设置缓存设置。 @RequestMapping(value = "/", method = RequestMethod.GET) public String welcome(HttpServletResponse response) { response.setHeader("Cache-Control", "no-transform, public, max-age=3600"); return "welcome"; }
  • 非常感谢。我将其更改为: httpServletResponse.setHeader("Cache-Control", "no-transform, public, max-age=3600");计数 += 1; return "Ale ma kota a kot ma ale a count" + String.valueOf(count);并且作为响应是 Cache-Control →no-transform, public, max-age=3600 但我认为它不起作用。重新加载后计数增加。
  • 好的。您如何验证响应缓存标头?通过在方法中使用计数器并增加它?理想情况下,您应该检查浏览器网络控制台并检查响应标头。 stackoverflow.com/questions/4423061/…是链接
  • 我的响应头是 :My Cache-Control:no-transform, public, max-age=3600 Content-Length:34 Content-Type:text/html;charset=UTF-8 Date:Tue , 2017 年 5 月 30 日 10:51:24 GMT Expires:0 Pragma:no-cache X-Content-Type-Options:nosniff X-Frame-Options:DENY X-XSS-Protection:1;模式=块
  • 我们已经设置了缓存头,只要禁用Pragma:no-cache,它应该可以工作

标签: spring spring-mvc spring-boot spring-security


【解决方案1】:

SpringSecurity 默认设置为no-cache 模式。

您可以在HttpServletResponse 对象中设置缓存设置。

@RequestMapping(value = "/", method = RequestMethod.GET) 
public String welcome(HttpServletResponse response) { 
    response.setHeader("Cache-Control", "no-transform, public, max-age=3600"); 
    return "welcome"; 
}

官方文档请参考this。

【讨论】:

  • 还有Prgama - no-cache header,也是默认设置。如果我在安全配置中禁用缓存,它将起作用,但我只想使用一种控制器方法。这就是现在的问题。顺便说一句,非常感谢您的回答
  • okay Pragma:no-cache 用于向后兼容 HTTP 1.0 版本。 Cache-Control 用于 HTTP1.1,Pragma 标头在没有 Cache-Control 标头的情况下工作。你的情况有点棘手,因为两者都是冲突的。
  • 好吧,你能不能试着把这个response.setHeader("Pragma", "cache");添加到你的控制器里试试
猜你喜欢
  • 2020-11-19
  • 2011-01-13
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2018-09-12
相关资源
最近更新 更多