Caching HTTP responses in a SpringMVC application

I would like my Spring controller to cache the returned content. I found a lot of questions on how to disable caching. I would like to know how to enable caching. My controller is as follows:

@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 added the line: httpServletResponse.setHeader("Cache-Control", "public"); to set caching, but in my browser, when I refresh this page, I still get the same result: 200 OK . How can I achieve a result of 304 not modified ? I can set the @ResponseStatus(value = HttpStatus.NOT_MODIFIED) annotation @ResponseStatus(value = HttpStatus.NOT_MODIFIED) for this method, but will it only be status or also actual caching?

+4
source share
1 answer

Quote 14.9.1 What is Cacheable :

public - indicates that the response can be cached by any cache, even if it is usually not cached or cached only in a cache that does not use shared access.

Basically, Cache-Control: public not enough, it only asks the browser to cache normally uncached resources, for example. over https.

HTTP caching is actually quite complicated and includes several other headers:

  • Cache-Control - discussed above

  • Expires - if this resource should be considered obsolete

  • Last-Modified - when a resource was changed

  • ETag - a unique resource tag changed in each revision

  • Vary - separate caching based on different headers

  • If-Modified-Since , If-None-Match , ...

I found a caching tutorial to be pretty complete. Not all headers are meant to be shared, and you have to be sure what you are doing. Therefore, I recommend using built-in solutions such as EhCache web caching .

It is also not recommended to contaminate your controller with such low-level parts.

+8
source

Source: https://habr.com/ru/post/1441091/


All Articles