Search code examples
javaspringrestspring-mvchttp-caching

Enable Http Cache in Spring Boot


From my client I'm querying some enums from the server. Now, I would like to cache these enums in the client as soon as they have been queried once on the server.

I tried to set Cache-Control as follows:

@CrossOrigin
@RequestMapping(value = "enums/{name}", method = RequestMethod.GET)
public List<String> getEnums( @PathVariable("name") String name, final HttpServletResponse response) {
    response.setHeader("Cache-Control", "max-age=3600");
    return myservice.findAllEnums(name);
}

The response header seems to be correctly set with Cache-control: max-age=3600. I also disabled all http headers in my security config as follows:

@Override 
protected void configure(final HttpSecurity http) throws Exception {     
http.headers().cacheControl().disable(); 
}

Unfortunately, the response is not cached in the browser. As soon as I'm querying the resource, the query is going to the server again.

Meanwhile, I removed Spring Security completly, but it still does not work. What I did not understand correctly? What else do I need to configure?


Solution

  • Ok, I noticed that it was working with IE, but not with Chrome. The problem with Chrome is that it sets Cache-control: max-age=0 on the request's header if you're refrehsing the page. This obviously prevents the data from being cached. I then created a simple html using a hyperlink to my application and refresehing it via this link. Thus, the cache worked as expected.