在 Tomcat 中通过 web.xml 配置缓存控制响应头

你可以在你的 Web 应用的 WEB-INF/web.xml 文件中,通过配置过滤器(Filter)来给特定资源(比如 index.html)添加缓存控制的响应头。

示例:配置一个简单的缓存控制过滤器给 index.html

1. 编写一个过滤器类

java 复制代码
java复制
package com.example.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class NoCacheFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化(可不实现)
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(response instanceof HttpServletResponse){
            HttpServletResponse httpResp = (HttpServletResponse) response;
            httpResp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
            httpResp.setHeader("Pragma", "no-cache"); // HTTP 1.0
            httpResp.setDateHeader("Expires", 0); // Proxies
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁(可不实现)
    }
}

2. 在 web.xml 中声明并映射该过滤器

xml 复制代码
xml复制
<filter>
    <filter-name>noCacheFilter</filter-name>
    <filter-class>com.example.filter.NoCacheFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>noCacheFilter</filter-name>
    <!-- 只拦截index.html -->
    <url-pattern>/index.html</url-pattern>
</filter-mapping>

这样,当访问 index.html 时,Tomcat 返回的响应头就带上了禁止缓存的指令,浏览器就会每次重新请求,不会触发 304。

相关推荐
码事漫谈20 小时前
别写Prompt了,现在流行给AI“写循环”
后端
Kyrie_Li21 小时前
Spring Boot Kafka 生产级配置全解析:从入门到精通
spring boot·后端·kafka
Coder_Shenshen1 天前
西门子S7CommPlus协议鉴权算法原理与流程详解
网络·后端·算法
yuhaiqiang1 天前
随手 vibecoding 的浏览器插件已经 6000 多次下载,聊聊他的产品设计
前端·后端·面试
geovindu1 天前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
卷无止境1 天前
C++ 存储类说明符(Storage Class Specifier)大横评
c++·后端
用户019027581611 天前
量化数据的 batch 接口有多好用?从 1 只到 500 只,批量拉数据的正确姿势
后端
rruining1 天前
Java设计模式——结构型
后端
卷无止境1 天前
C++ 编程的一大坑:非常量全局变量是"万恶之源"
c++·后端
Sinclair1 天前
认识安企CMS-系统和模板文件结构
后端