
本文解决 Spring Boot 项目中因模板名称不匹配或路径配置错误导致的 Error resolving template [users] 500 错误,重点说明控制器返回视图名、Thymeleaf 模板位置及 HTML 结构规范三者间的协同要求。
本文解决 spring boot 项目中因模板名称不匹配或路径配置错误导致的 `error resolving template [users]` 500 错误,重点说明控制器返回视图名、thymeleaf 模板位置及 html 结构规范三者间的协同要求。
在 Spring Boot + Thymeleaf 项目中,控制器方法返回的字符串(如 "users")并非文件名或 URL 路径,而是 逻辑视图名(view name),它将由 Thymeleaf 的 TemplateResolver 映射为实际模板文件路径。默认情况下,Spring Boot 自动配置 Thymeleaf 将视图名解析为 classpath:/templates/{viewName}.html。因此:
- 当 @GetMapping("/") 返回 "users" 时,Thymeleaf 会尝试加载 src/main/resources/templates/users.html;
- 若你实际只创建了 index.html,而控制器却返回 "users",则必然触发 TemplateInputException: Error resolving template [users] —— 这正是你遇到的核心问题。
✅ 正确做法有两种(任选其一):
方案一:统一视图名与文件名
将 src/main/resources/templates/index.html 重命名为 users.html,保持控制器不变:
@GetMapping("/")
public String AllUsers(Model model) {
model.addAttribute("listUsers", userService.getAllUsers());
return "users"; // → 对应 users.html
}方案二:修改控制器返回值匹配现有文件
保留 index.html 文件名,将控制器返回值改为 "index":
@GetMapping("/")
public String AllUsers(Model model) {
model.addAttribute("listUsers", userService.getAllUsers());
return "index"; // → 对应 index.html
}⚠️ 同时,请确保你的 HTML 模板符合 Thymeleaf 规范(否则即使路径正确也会渲染失败):
- 使用 th:each 遍历模型数据(而非空 <tbody>);
- 属性绑定使用 th:text="${...}",避免原生 HTML 文本硬编码;
- 表格结构需完整(<tr> 包裹 <td>,<thead> 内用 <tr><th>);
- WebJars 资源路径应以 / 开头(th:href="@{/webjars/...}"),否则相对路径可能解析失败。
以下是修正后的 users.html(推荐采用此命名并存放于 templates/ 目录下):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="UTF-8">
<title>Manager Site</title>
<link rel="stylesheet"
th:href="@{/webjars/bootstrap/5.2.3/css/bootstrap.min.css}">
</head>
<body>
<div class="container-fluid text-center mt-4">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Email</th>
<th>Name</th>
<th>Username</th>
<th>Password</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${listUsers}">
<td th:text="${user.id}"></td>
<td th:text="${user.email}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.password}"></td>
<td>
<a href="#" class="btn btn-sm btn-outline-primary">Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>? 补充验证要点:
- 确认 spring-boot-starter-thymeleaf 已添加至 pom.xml;
- 检查 application.properties 中未意外禁用 Thymeleaf(如 spring.thymeleaf.enabled=false);
- 确保 templates/ 目录位于 src/main/resources/ 下(不是 src/main/webapp/ 或 static/);
- 若使用 Lombok,请确认 IDE 已启用注解处理器,且 User 类能正确生成 getter 方法(Thymeleaf 依赖反射调用 getEmail() 等)。
遵循以上规范后,访问 http://localhost:8080/ 即可成功渲染用户列表页,彻底规避模板解析异常。


















