動態頁面(新聞、報表、用戶資料)若被瀏覽器/代理緩存,用戶會看到過期數據。必須明確告知客戶端「每次請求都重新獲取」。
<%@ page contentType="text/html;charset=UTF-8" %>
<%
// HTTP 1.1
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
// HTTP 1.0 相容
response.setHeader("Pragma", "no-cache");
// 過期時間設為過去
response.setDateHeader("Expires", 0);
%>
<html>...</html>
| 標頭 | 值 | 作用 |
|---|---|---|
| Cache-Control | no-cache, no-store, must-revalidate | 禁止緩存、禁止存儲、強制向源伺服器驗證 |
| Pragma | no-cache | HTTP 1.0 向後相容 |
| Expires | 0 或 -1 | 過期時間為 1970/1/1,視為已過期 |
<head>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
</head>
注意:Meta 標籤不被代理伺服器識別,僅影響瀏覽器緩存行為,優先級低於 HTTP 標頭。
@WebFilter("/*")
public class NoCacheFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse) res;
resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
resp.setHeader("Pragma", "no-cache");
resp.setDateHeader("Expires", 0);
chain.doFilter(req, res);
}
}
在 Filter 中排除靜態路徑,或配置 Tomcat DefaultServlet 設置 cacheTTL,利用 ETag/Last-Modified 實現協商緩存。
// jQuery
$.ajaxSetup({ cache: false }); // 自動加 _={timestamp} 參數
// 或手動
$.get("/api/data?" + new Date().getTime(), ...);
Expires 不設 Cache-Control → HTTP 1.1 客戶端可能忽略<body> 中寫 Meta → 必須在 <head>