即使设置了 Cache-Control,动态生成的 CSS 文件也不会被缓存
我有一个由 Spring 控制器动态生成的 CSS 文件。我在处理程序方法中设置了 Cache-Control 响应标头,但由于某种原因,我的 FireFox 在请求引用 CSS 文件而不是使用缓存版本时不断请求 CSS 文件。
这是代码。
@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());
}
}
HTML 文件以通常的方式引用 CSS 文件。
<link rel="stylesheet" type="text/css" href="/foo.css" />
我在这里做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我是OP,但经过进一步研究,我决定你需要自己实现这个。您需要让服务器生成 304 响应代码,以便客户端浏览器使用缓存资源,但 Spring 和 Tomcat 都不支持这种开箱即用的方式。
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.
首先,浏览器和代理服务器不需要遵守标头上的 HTTP 缓存控制。他们只是提供建议。也许浏览器忽略了缓存请求并遵循他的偏好配置。
另一种方法是将随机属性添加到由 javascript 生成的 url 中。类似于:
这是一篇关于此主题的好文章 http://code.google .com/speed/page-speed/docs/caching.html
Well, first of all, browsers and proxy servers do not need to comply with HTTP Cache controls putted on the headers. They are only advisory. Maybe the browser is ignoring the cache request and obeying what is configured on his preferences.
Another way to do that is putting a random attribute to the url, generated by javascript. Something like:
Here's a nice article about this subject http://code.google.com/speed/page-speed/docs/caching.html
Spring 支持这一点已经有一段时间了,并且在最近的版本中得到了改进。请参阅 有关此的参考文档。
This has been supported by Spring for quite a while now, and it has been improved in recent versions. See the reference documentation about this.