Java Spring Boot:我正在尝试将CacheControl标头添加到Response
我在
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所述:
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
其中一个由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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |