response.setDateHeader() - 缓存不起作用
我希望缓存网页中的 .png 文件。我在 web.xml 中添加了以下条目
<filter>
<filter-name>ContentFilter</filter-name>
<filter-class>filters.ContentFilter</filter-class>
<init-param>
<description>Add an Expires Header</description>
<param-name>expiryDate</param-name>
<param-value>Fri, 30 Apr 2021 20:00:00 GMT</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ContentFilter</filter-name>
<url-pattern>*.png</url-pattern>
</filter-mapping>
在 init() 中按以下方式设置 expiryDate 字段值
String expiryDateStr = filterConfig.getInitParameter("expiryDate");
SimpleDateFormat format = new SimpleDateFormat(
"EEE, d MMM yyyy HH:mm:ss Z");
try {
Date d = format.parse(expiryDateStr);
expiryDate = d.getTime();
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
doFilter() 是:
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain filChain) throws IOException, ServletException {
logger.debug("doFilter()");
logger.info(((HttpServletRequest)req).getRequestURL().toString());
filChain.doFilter(req, res);
if (res instanceof HttpServletResponse) {
HttpServletResponse response = (HttpServletResponse) res;
logger.info(((HttpServletRequest)req).getRequestURL().toString());
response.setDateHeader("Expires", expiryDate);
}
}
我的问题是,每当我在浏览器中刷新网页时,客户端都会不断请求 .png 文件。猜猜我的过滤器不起作用。这个配置正确吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看您的代码,可能的罪魁祸首是您在 servlet 处理请求之后设置响应标头。此时添加标头已经太晚了,响应数据已经发送。
将
response.setDateHeader
移至filChain.doFilter
之前,并且应发送标头。话虽如此,众所周知,这些东西很难做好。浏览器对 HTTP 缓存有各种不同的行为,发送您认为正确的标头并不总是能达到您想要的效果。
尝试使用 HTTP 标头嗅探工具(例如优秀的“Live HTTP headers” Firefox 插件)来查看实际来回的内容。
Looking at your code, a likely culprit is that you're setting the response header after the request has been processed by the servlet. It's too late to add a header at the point, the response data is already sent.
Move the
response.setDateHeader
to before thefilChain.doFilter
, and the header should be sent.Having said that, this stuff is notoriously tricky to get right. Browsers have all sort of different behaviours for HTTP caching, and sending what you think is the right header doesn't always have the effect you're looking for.
Try using an HTTP header sniffing tool (like the excellent "Live HTTP Headers" plugin for firefox) to see what's actually going back and forth.
“到期”日期不应超过未来一年。
请参阅 http://www.w3.org/Protocols/rfc2616/ 中的第 14.21 节过期rfc2616-sec14.html
'Expires' date should not be more than one year in future.
See Section 14.21 Expires in http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html