I would like my Spring Controller to cache the content which returns. I have found a lot of questions how to disable caching. I would like to know how to enable caching. My Controller looks like this one:
@Controller
public class SimpleController {
@RequestMapping("/webpage.htm")
public ModelAndView webpage(HttpServletRequest request,
HttpServletResponse response) {
ModelAndView mav = new ModelAndView("webpage");
httpServletResponse.setHeader(“Cache-Control”, “public”);
//some code
return mav;
}
}
As you can see I have added the line: httpServletResponse.setHeader(“Cache-Control”, “public”); to set caching but in my browser when I refresh this page I am still getting the same status result: 200 OK. How can I achieve result 304 not modified? I can set annotation @ResponseStatus(value = HttpStatus.NOT_MODIFIED) on this method but will it be only status or also actual caching?
Quoting 14.9.1 What is Cacheable:
Basically the
Cache-Control: publicis not enough, it only asks the browser to cache normally not cached resources, e.g. over HTTPS.Caching in HTTP is actually quite complex and it involves several other headers:
Cache-Control– discussed aboveExpires– when given resource should be considered staleLast-Modified– when was resource last modifiedETag– unique tag of resource, changed in every revisionVary– separate caching based on different headersIf-Modified-Since,If-None-Match, …I found Caching Tutorial to be pretty comprehensive. Not all headers are meant to be used together and you have to be really sure what you are doing. Thus I recommend using built-in solutions like EhCache web caching.
Also it’s not a good idea to pollute your controller with such low-level details.