
Spring Boot 应用返回 404 而非预期 Thymeleaf 模板页面,通常是因为缺少 spring-boot-starter-thymeleaf 依赖,导致模板引擎未自动配置,静态资源路径或视图解析器失效。
spring boot 应用返回 404 而非预期 thymeleaf 模板页面,通常是因为缺少 `spring-boot-starter-thymeleaf` 依赖,导致模板引擎未自动配置,静态资源路径或视图解析器失效。
在 Spring Boot 中,视图渲染并非开箱即用——它依赖于自动配置模块的激活。你当前的代码逻辑完全正确:控制器使用 @Controller 注解、返回逻辑视图名 "login",且 HTML 文件已按约定放置在 src/main/resources/templates/login.html(注意:Thymeleaf 默认查找 resources/templates/,而非 webapp/ 或 static/)。但关键缺失在于:项目未引入 Thymeleaf 启动器依赖。
Spring Boot 的 spring-boot-starter-thymeleaf 不仅提供 Thymeleaf 引擎本身,更重要的是触发 ThymeleafAutoConfiguration,该配置会自动注册:
- ThymeleafViewResolver(将字符串视图名如 "login" 解析为 templates/login.html);
- TemplateEngine 实例;
- 默认前缀(classpath:/templates/)与后缀(.html)。
若该依赖缺失,Spring MVC 将无法识别 .html 模板,请求 / 时找不到匹配视图,最终由默认错误处理器返回 Whitelabel 404 页面。
✅ 正确做法:在 pom.xml 中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>添加后重启应用,无需额外配置即可生效(Spring Boot 2.6+ 默认启用 Thymeleaf 缓存禁用开发模式,生产环境可按需调整 spring.thymeleaf.cache=false)。
⚠️ 补充注意事项:
- 确保 login.html 文件编码为 UTF-8,且 <html> 标签含 xmlns:th="https://www.thymeleaf.org" 命名空间(你已正确配置);
- 检查包扫描:@SpringBootApplication 默认扫描主类所在包及其子包,你的 UserController 在 com.example.demo.user 下,而主类在 com.example.demo,因此扫描正常;
- 若仍 404,请验证文件路径是否为 src/main/resources/templates/login.html(不是 src/main/resources/static/login.html —— 后者属静态资源,不经过视图解析);
- 可通过 spring.mvc.view.prefix 和 spring.mvc.view.suffix 自定义视图路径(一般无需)。
总结:Spring Boot 的“约定优于配置”高度依赖 starter 依赖的自动装配。视图渲染失败,第一步永远先检查对应 starter 是否就位——本例中,一行依赖即可解决核心问题。

















