我在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
我做错了什么?有人可以帮我一把。
答案 0 :(得分:14)
只需将以下内容添加到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);