商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > Spring Boot 中 Thymeleaf 模板无法解析问题的完整解决方案

Spring Boot 中 Thymeleaf 模板无法解析问题的完整解决方案

  发布于2026-07-11 阅读(0)

扫一扫,手机访问

本文详解 Spring Boot 项目中因模板路径、命名或 Thymeleaf 配置不当导致的 Error resolving template [users] 500 错误,并提供可立即生效的修复方案。

老实说,这个问题其实挺常见的。在 Spring Boot 整合 Thymeleaf 的项目里,当控制器返回一个逻辑视图名时,比如 "users",Thymeleaf 就会默认去 src/main/resources/templates/ 目录下,找一个叫 users.html 的文件。如果你的代码抛出了这个错误:

Error resolving template [users], template might not exist or might not be accessible...

问题很明确:Spring Boot 在 templates/ 目录下根本找不到 users.html 这个文件。等等,你以为你放了对吗?是不是文件名写错了?——没错,如果你实际的文件名是 index.html,那这就是根因所在。

✅ 正确做法:保持视图名与文件名严格一致

假设你的控制器方法是这样写的:

@GetMapping("/")
public String AllUsers(Model model) {
    model.addAttribute("listUsers", userService.getAllUsers());
    return "users"; // ← Thymeleaf 将尝试加载 templates/users.html
}

那么,你必须把 HTML 文件重命名为 users.html,并且放在 src/main/resources/templates/ 目录下。注意,不是 index.html。如果你希望根路径 / 渲染一个首页,千万别指望 Thymeleaf 会自动映射 index.html——这个机制只对静态资源生效,动态模板必须显式返回对应的视图名。

⚠️ 注意:index.html 放在 templates/ 目录下,并不会被 Spring MVC 自动识别为根路径视图。它只有放在 static/public/ 下,才可能作为静态首页生效,而且那样的话,它里面就不能使用 Thymeleaf 表达式了。

✅ 修复后的 users.html(推荐完整版)

确认文件路径为 src/main/resources/templates/users.html,内容如下(已经修正了语法,增强了可读性和安全性):




    
    Manager Site
    
    


User Management

ID Email Name Username Password Actions
1 user@example.com John Doe johndoe •••••••• Edit
No users found.

? 关键检查清单

  • ✅ 确认 users.html 存在于 src/main/resources/templates/(不是 static/,也不是 templates/index.html
  • ✅ 确保 spring-boot-starter-thymeleaf 已正确添加到 pom.xml
    
        org.springframework.boot
        spring-boot-starter-thymeleaf
    
  • ✅ 如果使用 WebJars,确认 spring-boot-starter-web 已引入,且 spring.resources.static-locations 没有覆盖默认配置
  • ✅ 实体类字段名需要与 Thymeleaf 表达式严格匹配。比如,你代码里用的是 username,那 Thymeleaf 里就得写 ${user.username}。如果字段名是 userName,那就得写成 ${user.userName}。建议统一命名,或者直接用 Lombok 的 @Data 自动生成 getter/setter,然后仔细校验一下字段名

? 补充说明:关于 index.html 的正确定位

如果你想让根路径 / 映射到 index.html,有两条合规的路径:

  1. 静态首页(无服务端逻辑):把 index.html 放到 src/main/resources/static/src/main/resources/public/。这种情况下,它由 ResourceHttpRequestHandler 提供,不经过 Thymeleaf,所以里面不能写 Thymeleaf 表达式。
  2. 动态首页(含模型数据):保留 templates/index.html,然后把控制器改成:
    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("listUsers", userService.getAllUsers());
        return "index"; // ← 返回 "index",对应 index.html
    }

核心原则其实就一句话:控制器返回的视图名,必须等于 templates/ 目录下的文件名(不含扩展名)。命名不一致,模板解析失败是必然的。修复命名后,重启应用,应该就能正常访问 http://localhost:8080/ 了。

本文转载于:https://www.php.cn/faq/2805577.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注