发布于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 表达式了。
确认文件路径为 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
spring-boot-starter-web 已引入,且 spring.resources.static-locations 没有覆盖默认配置username,那 Thymeleaf 里就得写 ${user.username}。如果字段名是 userName,那就得写成 ${user.userName}。建议统一命名,或者直接用 Lombok 的 @Data 自动生成 getter/setter,然后仔细校验一下字段名如果你想让根路径 / 映射到 index.html,有两条合规的路径:
index.html 放到 src/main/resources/static/ 或 src/main/resources/public/。这种情况下,它由 ResourceHttpRequestHandler 提供,不经过 Thymeleaf,所以里面不能写 Thymeleaf 表达式。templates/index.html,然后把控制器改成:@GetMapping("/")
public String home(Model model) {
model.addAttribute("listUsers", userService.getAllUsers());
return "index"; // ← 返回 "index",对应 index.html
}核心原则其实就一句话:控制器返回的视图名,必须等于 templates/ 目录下的文件名(不含扩展名)。命名不一致,模板解析失败是必然的。修复命名后,重启应用,应该就能正常访问 http://localhost:8080/ 了。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8