You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.7.+嵌入式Tomcat自定义context.xml未生效,求解决服务器信息泄露

解决Spring Boot嵌入式Tomcat加载自定义context.xml并屏蔽服务器信息的问题

核心问题原因

嵌入式Tomcat和独立部署的Tomcat逻辑不同,它不会自动扫描classpath下的META-INF/context.xml,所以你之前放置的文件即便被打包进jar包,Tomcat也不会主动加载生效。

两种解决方案

方案一:直接代码配置屏蔽服务器信息(更简单可靠)

不用折腾context.xml,直接在Spring Boot配置类里添加阀门配置,一步实现屏蔽:

import org.apache.catalina.valves.ErrorReportValve;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TomcatSecurityConfig implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        ErrorReportValve errorValve = new ErrorReportValve();
        errorValve.setShowServerInfo(false);
        factory.addContextValves(errorValve);
    }
}

方案二:强制加载自定义context.xml

如果必须使用自定义的context.xml,先确保你的配置文件里包含屏蔽规则:

<!-- src/main/resources/META-INF/context.xml -->
<Context>
    <Valve className="org.apache.catalina.valves.ErrorReportValve" showServerInfo="false"/>
    <!-- 其他你需要的配置 -->
</Context>

然后创建配置类,手动让Tomcat加载这个文件:

import org.apache.catalina.Context;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;

@Configuration
public class TomcatContextConfig implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        factory.addContextCustomizers((Context context) -> {
            try {
                ClassPathResource resource = new ClassPathResource("META-INF/context.xml");
                File contextFile = resource.getFile();
                context.setConfigFile(contextFile.toURI().toURL());
            } catch (IOException e) {
                throw new RuntimeException("加载自定义context.xml失败", e);
            }
        });
    }
}

验证方式

启动应用后,故意触发一个500错误(比如写个抛出异常的接口),查看错误页面或响应内容,确认服务器相关信息已被屏蔽。

内容的提问来源于stack exchange,提问作者JJ36

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 14:02:29