Java spring boot: I’m trying to add the CacheControl header to the responseentity
I'm not very good in Java spring, but I want to add cache control header to my 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);
}
}
I added two lines of code for httpheaders. Now I get two cache control headers in the response:
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
What did I do wrong? Can anyone help me?
Solution
TL; DR
Just add the following to the application properties:
security.headers.cache=false
More details
As described in the 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
One of them is provided by spring security If you don't like them, you can disable the default cache control header in websecurityconfigureradapter:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// Other configurations
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// Other configurations
.headers()
.cacheControl().disable();
}
}
Since you are using spring boot, you can use security headers.* Property implements the same function To disable the default cache control header, simply add the following to the application properties:
security.headers.cache=false
In addition, a more common way to add cache control headers is to use the new CacheControl Builder:
ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(600,TimeUnit.SECONDS))
.body(body);
