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

use*_*622 9 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);
        }
}
Run Code Online (Sandbox Code Playgroud)

我添加了两行代码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
Run Code Online (Sandbox Code Playgroud)

我做错了什么?有人能帮助我吗?

Ali*_*ani 16

TL; DR

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

security.headers.cache=false
Run Code Online (Sandbox Code Playgroud)

更多细节

正如Spring Security文档所述:

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
Run Code Online (Sandbox Code Playgroud)

现在我在响应中得到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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

security.headers.cache=false
Run Code Online (Sandbox Code Playgroud)

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

ResponseEntity.ok()
              .cacheControl(CacheControl.maxAge(600, TimeUnit.SECONDS))
              .body(body);
Run Code Online (Sandbox Code Playgroud)