在 JSP 中添加 Expires 或 Cache-Control 标头 [英] Add an Expires or a Cache-Control header in JSP
问题描述
如何在 JSP 中添加 Expires
或 Cache-Control
标头?我想在包含页面中为我的静态组件(例如图像、CSS 和 JavaScript 文件)添加一个远期到期日期.
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 页面的浏览器缓存,请创建一个映射到 url-pattern
的 Filter
*.jsp
并在 doFilter()
方法中基本上执行以下操作:
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:
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.
这样您就不需要将其复制粘贴到所有 JSP 页面上并用 scriptlets 将它们弄乱.
This way you don't need to copypaste this over all JSP pages and clutter them with scriptlets.
要为 CSS 和 JS 等静态组件启用浏览器缓存,请将它们全部放在一个公共文件夹中,例如 /static
或 /resources
并创建一个 Filter
映射在 /static/*
或 /resources/*
的 url-pattern
上,并在 /resources/*
中基本上执行以下操作代码>doFilter() 方法:
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:
httpResponse.setDateHeader("Expires", System.currentTimeMillis() + 604800000L); // 1 week in future.
另见:
这篇关于在 JSP 中添加 Expires 或 Cache-Control 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!