在 JSP 中添加 Expires 或 Cache-Control 标头 [英] Add an Expires or a Cache-Control header in JSP

查看:28
本文介绍了在 JSP 中添加 Expires 或 Cache-Control 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 JSP 中添加 ExpiresCache-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-patternFilter*.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆