萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 防止瀏覽器緩存的完整方案:HTTP 標頭與 Meta 標籤雙重保險

為何需要禁用緩存?

動態頁面(新聞、報表、用戶資料)若被瀏覽器/代理緩存,用戶會看到過期數據。必須明確告知客戶端「每次請求都重新獲取」。

方案一:JSP 中設置 HTTP 響應標頭(推薦,最有效)

<%@ 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-Controlno-cache, no-store, must-revalidate禁止緩存、禁止存儲、強制向源伺服器驗證
Pragmano-cacheHTTP 1.0 向後相容
Expires0 或 -1過期時間為 1970/1/1,視為已過期

方案二:HTML Meta 標籤(靜態頁/不支援動態設置時備用)

<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 標頭。

進階場景處理

1. 針對特定資源類型(Filter 統一攔截)

@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);
    }
}

2. 允許緩存靜態資源(CSS/JS/圖片)

在 Filter 中排除靜態路徑,或配置 Tomcat DefaultServlet 設置 cacheTTL,利用 ETag/Last-Modified 實現協商緩存。

3. AJAX 請求防緩存

// jQuery
$.ajaxSetup({ cache: false }); // 自動加 _={timestamp} 參數
// 或手動
$.get("/api/data?" + new Date().getTime(), ...);

常見誤區

  • 只設 Expires 不設 Cache-Control → HTTP 1.1 客戶端可能忽略
  • 在 <body> 中寫 Meta → 必須在 <head>
  • 認為 Meta 能控制 CDN/代理 → 無效,需配置 Edge 節點規則
copyright © 萬盛學電腦網 all rights reserved