在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
*。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 <这样的公共文件夹中/ code>或
/ resources
并创建一个过滤器
,它映射在上url-pattern
of / static / *
或 / 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.
参见:
- Making sure a web page is not cached, across all browsers.
- Webapplication performance tips and tricks.
这篇关于在JSP中添加Expires或Cache-Control标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!