我在
Java Spring中不是很好,但我想在我的ResponseEntity中添加Cache-Control标头.
@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
我做错了什么?有人能帮助我吗?
解决方法
TL; DR
只需将以下内容添加到application.properties:
security.headers.cache=false
更多细节
正如Spring Security documentation所述:
Spring Security allows users to easily inject the default security
headers to assist in protecting their application. The default for
Spring Security is to include the following headers:
Cache-Control: no-cache,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
now I get 2 CacheControl headers in my response
其中一个由Spring Security提供.如果您不喜欢它们,可以在WebSecurityConfigurerAdapter中禁用默认的Cache-Control标头:
@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);