Java + Spring Boot:我正在尝试将CacheControl标头添加到ResponseEntity

时间:2016-06-30 19:28:10

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

我在Java + Spring中不太好,但我想在Cache-Control添加ResponseEntity标题。

@RequestMapping(value = "/data/{id}", method = GET")
public ResponseEntity<String> getData(@PathVariable("id") String id) {
    try {
            ...
            HttpHeaders headers = new HttpHeaders();
            headers.setCacheControl("max-age=600");

            return new ResponseEntity<String>(body, headers, HttpStatus.OK);
        }
}

我为HttpHeaders添加了两行代码,现在我的回复中有两个Cache-Control标题:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
Cache-Control: max-age=600
Content-Type: application/json;charset=UTF-8
Content-Length: 18223
Date: Wed, 29 Jun 2016 21:56:57 GMT

我做错了什么?有人可以帮我一把。

1 个答案:

答案 0 :(得分:14)

TL; DR

只需将以下内容添加到application.properties

即可
security.headers.cache=false

更多详情

正如Spring Security documentation所述:

  

Spring Security允​​许用户轻松注入默认安全性   标题有助于保护其应用程序。默认值为   Spring Security包括以下标题:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
  

现在我在响应中获得了2个CacheControl标头

其中一个由Spring Security提供。如果您不喜欢它们,可以在Cache-Control中停用默认的WebSecurityConfigurerAdapter标题:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // Other configurations

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // Other configurations
                .headers()
                    .cacheControl().disable();
    }
}

由于您使用的是Spring Boot,因此可以使用security.headers.*属性实现相同功能。要停用该默认Cache-Control标头,只需将以下内容添加到application.properties

即可
security.headers.cache=false

此外,更加惯用的添加Cache-Control标头的方法是使用新的cacheControl构建器:

ResponseEntity.ok()
              .cacheControl(CacheControl.maxAge(600, TimeUnit.SECONDS))
              .body(body);