Java 在 JSP 中添加 Expires 或 Cache-Control 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3055268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add an Expires or a Cache-Control header in JSP
提问by Sam
How do you add an Expires
or a Cache-Control
header in JSP? I want to add a far-future expiration date in an include page for my static components such as images, CSS and JavaScript files.
你如何在 JSP 中添加一个Expires
或一个Cache-Control
标题?我想在包含页面中为我的静态组件(如图像、CSS 和 JavaScript 文件)添加一个未来的到期日期。
采纳答案by BalusC
To disable browser cache for JSP pages, create a Filter
which is mapped on an url-pattern
of *.jsp
and does basically the following in the doFilter()
method:
要禁用 JSP 页面的浏览器缓存,请创建一个Filter
映射到url-pattern
of*.jsp
并在doFilter()
方法中基本上执行以下操作的对象:
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0); // Proxies.
This way you don't need to copypaste this over all JSP pages and clutter them with scriptlets.
这样您就不需要将其复制粘贴到所有 JSP 页面上并用scriptlet 将它们弄乱。
To enable browser cache for static components like CSS and JS, put them all in a common folder like /static
or /resources
and create a Filter
which is mapped on an url-pattern
of /static/*
or /resources/*
and does basically the following in the doFilter()
method:
要为 CSS 和 JS 等静态组件启用浏览器缓存,请将它们全部放在一个公共文件夹中,例如/static
or/resources
并创建一个Filter
映射到url-pattern
of /static/*
or 的一个,/resources/*
并在doFilter()
方法中基本上执行以下操作:
httpResponse.setDateHeader("Expires", System.currentTimeMillis() + 604800000L); // 1 week in future.
See also:
也可以看看:
回答by Darin Dimitrov
<%
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
%>
回答by mp31415
Servlet containers like Tomcat come with a set of predefined filters. See for example Expires Filter. It may be easier to use existing one than to create your own similar filter.
像 Tomcat 这样的 Servlet 容器带有一组预定义的过滤器。参见例如Expires Filter。使用现有的过滤器可能比创建自己的类似过滤器更容易。
回答by User1985
<%
response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
response.setHeader("Pragma", "no-cache"); //HTTP 1.0
response.setDateHeader("Expires", 0); //prevents caching at the proxy server
%>