如何在Java Servlet应用中关闭TomCat的索引文件自动服务
关闭TomCat索引文件自动服务功能的方法
传统独立TomCat部署场景
如果你的Web应用部署在独立TomCat服务器上,可通过修改欢迎页配置禁用自动返回index.html的行为:
修改项目本地配置(推荐,仅影响当前应用)
打开项目的WEB-INF/web.xml,找到<welcome-file-list>节点,移除其中的index.html条目,或者直接注释/删除整个节点:<!-- 修改前的默认配置 --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 修改后:移除index.html,保留其他欢迎页(可选) --> <welcome-file-list> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 或者直接禁用所有默认欢迎页 --> <!-- <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> -->修改TomCat全局配置(影响所有部署应用)
打开TomCat安装目录下的conf/web.xml,执行上述相同的修改操作。
Spring Boot内嵌TomCat场景
如果使用Spring Boot内嵌TomCat,有两种配置方式:
通过配置文件禁用
在application.properties中添加:server.servlet.welcome-page.enabled=false或者在
application.yml中添加:server: servlet: welcome-page: enabled: false通过配置类自定义TomCat行为
创建配置类清除默认欢迎页列表:import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TomcatWelcomePageConfig { @Bean public WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatWelcomePageCustomizer() { return factory -> factory.getTomcatContext().setWelcomeFiles(null); } }
生效说明
完成配置修改后重启TomCat服务,访问应用根路径时将不再自动返回index.html,而是执行你自定义的根路径请求映射逻辑。
内容的提问来源于stack exchange,提问作者G H
相关产品推荐
相关产品推荐

