Search code examples
javaspringcache-control

Dynamically generated CSS file is not cached even after setting Cache-Control


I have a CSS file dynamically generated by a Spring controller. I set the Cache-Control response header in the handler method but for some reason my FireFox keeps requesting the CSS file when requesting an HTML file that has a reference to it instead of using the cached version.

Here's the code.

@Controller
@RequestMapping("/foo.css")
public class FooController {
    @RequestMapping(method = RequestMethod.GET)
    public void show(HttpServletResponse response) {
        try {
            response.setHeader("Cache-Control", "max-age=3600");
            response.getWriter().println("this is a test.");
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(new Date());
    }
}

And the HTML file references the CSS file in the usual way.

<link rel="stylesheet" type="text/css" href="/foo.css" />

What am I doing wrong here?


Solution

  • I'm the OP, but after further research, I've decided that you need to implement this yourself. You need to have the server generate a 304 response code for the client browser to use a cached resource, but neither Spring nor Tomcat support this out-of-box.