在 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。

相关推荐
Livingbody7 分钟前
基于【ERNIE-4.5-VL-28B-A3B】模型的图片内容分析系统
后端
你的人类朋友1 小时前
🍃Kubernetes(k8s)核心概念一览
前端·后端·自动化运维
追逐时光者2 小时前
面试第一步,先准备一份简洁、优雅的简历模板!
后端·面试
慕木兮人可3 小时前
Docker部署MySQL镜像
spring boot·后端·mysql·docker·ecs服务器
发粪的屎壳郎3 小时前
ASP.NET Core 8 轻松配置Serilog日志
后端·asp.net·serilog
倔强青铜三4 小时前
苦练Python第4天:Python变量与数据类型入门
前端·后端·python
倔强青铜三4 小时前
苦练Python第3天:Hello, World! + input()
前端·后端·python
倔强青铜三4 小时前
苦练Python第2天:安装 Python 与设置环境
前端·后端·python
Kookoos4 小时前
ABP VNext + .NET Minimal API:极简微服务快速开发
后端·微服务·架构·.net·abp vnext
倔强青铜三5 小时前
苦练Python第1天:为何要在2025年学习Python
前端·后端·python