Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching HTTP reponses in a SpringMVC app

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?

like image 372
woyaru Avatar asked Feb 18 '23 18:02

woyaru


1 Answers

Quoting 14.9.1 What is Cacheable:

public - Indicates that the response MAY be cached by any cache, even if it would normally be non-cacheable or cacheable only within a non- shared cache.

Basically the Cache-Control: public is 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 above

  • Expires - when given resource should be considered stale

  • Last-Modified - when was resource last modified

  • ETag - unique tag of resource, changed in every revision

  • Vary - separate caching based on different headers

  • If-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.

like image 59
Tomasz Nurkiewicz Avatar answered Feb 27 '23 11:02

Tomasz Nurkiewicz