HTTP 響應頭緩存關鍵字段
| Header | 版本 | 常用值 | 說明 |
| Cache-Control | HTTP/1.1 | no-cache, no-store, public, private, max-age, must-revalidate | 主流緩存控制指令 |
| Pragma | HTTP/1.0 | no-cache | 向下兼容,僅請求頭有效 |
| Expires | HTTP/1.0 | GMT 日期 | 絕對過期時間,受客戶端時鐘影響 |
| Last-Modified | HTTP/1.0 | GMT 日期 | 資源最後修改時間,配合 If-Modified-Since |
| ETag | HTTP/1.1 | 實體標籤 | 強/弱驗證器,配合 If-None-Match |
Cache-Control 常用指令詳解
no-cache:強制向源服務器驗證(可配合 ETag),不直接使用緩存
no-store:絕對禁止緩存(含磁盤/內存),敏感數據必設
public:允許瀏覽器、代理服務器緩存
private:僅允許瀏覽器終端緩存,代理不可緩存
max-age=秒數:相對過期時間,優先級高於 Expires
must-revalidate:過期後必須回源驗證,不可使用陈旧副本
Servlet 動態設置緩存策略範例
response.setDateHeader("Last-Modified", System.currentTimeMillis());
response.setDateHeader("Expires", System.currentTimeMillis() + 3600_000); // 1 小時
response.setHeader("Cache-Control", "public, max-age=3600");
// 禁止緩存組合拳
// response.setHeader("Pragma", "no-cache");
// response.setDateHeader("Expires", 0);
// response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
HTML Meta 標籤模擬 HTTP 頭(適用於無法控制服務器響應頭的靜態頁)
<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 Header 為準。
Meta 標籤其他常用用法
| 屬性 | 用途 | 範例 |
| name="keywords" | SEO 關鍵詞 | <meta name="keywords" content="Java,教程"> |
| name="description" | SEO 描述 | <meta name="description" content="Java 緩存控制指南"> |
| name="viewport" | 移動端適配 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| http-equiv="refresh" | 定時跳轉 | <meta http-equiv="refresh" content="5;url=/target"> |
| http-equiv="X-UA-Compatible" | IE 渲染模式 | <meta http-equiv="X-UA-Compatible" content="IE=edge"> |