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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:02:40  来源:igfitidea点击:

Add an Expires or a Cache-Control header in JSP

javajsphttpcache-control

提问by Sam

How do you add an Expiresor a Cache-Controlheader 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 Filterwhich is mapped on an url-patternof *.jspand does basically the following in the doFilter()method:

要禁用 JSP 页面的浏览器缓存,请创建一个Filter映射到url-patternof*.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 /staticor /resourcesand create a Filterwhich is mapped on an url-patternof /static/*or /resources/*and does basically the following in the doFilter()method:

要为 CSS 和 JS 等静态组件启用浏览器缓存,请将它们全部放在一个公共文件夹中,例如/staticor/resources并创建一个Filter映射到url-patternof /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
%>