Web.xml welcome-file-list 默认欢迎页面配置

4次阅读

web.xml中welcome-file-list不生效,主因是容器未加载web.xml(如tomcat 9+、spring boot默认不扫描),或文件不存在、路径错误、大小写不符、权限不足、被spring boot欢迎页逻辑覆盖。

Web.xml welcome-file-list 默认欢迎页面配置

web.xml 里 welcome-file-list 不生效?先看容器是否加载了 web.xml

Tomcat 9+、jetty 10+ 或 Spring Boot 内嵌容器默认不扫描 web.xml,哪怕你写了 welcome-file-list,它根本没被读取。不是配置错,是压根没进解析流程。

实操建议:

  • 确认项目是传统 WAR 部署(非 Spring Boot 的 jar 启动),且 web.xmlWEB-INF/web.xml 路径下
  • Spring Boot 项目若强行要用 web.xml,得用 servletWebServerFactory 手动启用,但更推荐用 @Controller + return "index" 替代
  • Tomcat 8.5+ 默认开启 metadata-complete="false",但如果你在 web.xml 根标签写了 metadata-complete="true",又没配全注解等效项,欢迎页也会静默失效

welcome-file-list 中的文件名必须真实存在且可被容器访问

它不走 Spring mvc 的视图解析,也不触发拦截器或过滤器,只做最底层的静态资源匹配。写 index.jsp,但项目里只有 index.html?404。

常见错误现象:

  • 浏览器显示 404,但控制台无报错 —— 容器根本没找到匹配文件,连日志都懒得打
  • 写了 home.do,期望转发到 Servlet,但 welcome-file-list 只接受静态路径或 JSP,不支持后缀映射
  • 路径含子目录如 pages/index.html,实际必须写成 pages/index.html,不能省略 pages/,也不能写成 /pages/index.html(开头斜杠会被忽略)

多个 welcome-file 的匹配顺序和优先级

容器从上到下逐个试,第一个「存在且可读」的就返回,不继续往后找。顺序错了,可能永远轮不到你真正想设的页面。

使用场景示例:你想优先 index.html,降级到 index.jsp,最后兜底 default.htm

<welcome-file-list>   <welcome-file>index.html</welcome-file>   <welcome-file>index.jsp</welcome-file>   <welcome-file>default.htm</welcome-file> </welcome-file-list>

注意:

  • 文件名区分大小写,Index.htmlindex.html(尤其 linux 环境)
  • 如果 index.html 存在但权限为只读(如部署用户无读取权),容器会跳过它,尝试下一个 —— 这类问题常被忽略
  • 某些旧版 Tomcat 对空格或中文文件名支持差,尽量用纯 ASCII 命名

与 Spring Boot 或 Spring MVC 共存时,welcome-file-list 很可能被绕过

Spring Boot 2.0+ 默认注册了 WebMvcAutoConfiguration,它内置的欢迎页逻辑(查 Static/index.htmltemplates/index.html)会早于 web.xml 生效。哪怕你打包成 WAR 并部署到外部 Tomcat,只要用了 spring-boot-starter-web,这个自动配置就还在。

实操判断方法:

  • 启动日志搜 Initializing Spring DispatcherServlet —— 出现了,说明 MVC 已接管请求分发
  • 删掉 src/main/resources/static/index.html,再访问根路径,如果还是显示它,那基本确定是 Spring Boot 的欢迎页逻辑在起作用,不是 welcome-file-list
  • 真要强制走 web.xml,得在 application.properties 关掉: spring.mvc.welcome-page-static-path=(留空),并确保没配 spring.web.resources.static-locations 干扰

复杂点在于:web.xml 和 Spring 的欢迎页机制互不感知,出问题时你得先分清当前生效的是哪一层 —— 日志里没提示,得靠删文件、改路径、抓请求响应头来交叉验证。

text=ZqhQzanResources