今天练习 Spring Boot Thymeleaf 时,项目启动后页面访问出错,网上搜了一大堆发现根本解决不了问题.
报错信息:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Aug 03 23:18:20 CST 2019
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/users/list.html]")
最后,发现一旦使用 Thymeleaf 模板语言赋值时,如果当前变量不存在,就会出错。修改前代码片段如下:
<!-- 列表为空时 给出提示 -->
<tr th:if="${userModel.userList.size()} eq 0">
<td colspan="3">没有用户信息!</td>
</tr>
<tr th:each="user:${userModel.userList}">
<td th:text="${user.id}"></td>
<td th:text="${user.email}"></td>
<td th:text="${user.name}"></td>
</tr>
在传入参数后面加上一个英文问号,形成类似于三目运算,如果 user 不为空,则进行取值.
当参数取值层级较多时,也可以是 userModel?.userList?.size() 这种.
<tr th:if="${userModel?.userList?.size()} eq 0">
<td colspan="3">没有用户信息!</td>
</tr>
<tr th:each="user:${userModel?.userList}">
<td th:text="${user?.id}"></td>
<td th:text="${user?.email}"></td>
<td th:text="${user?.name}"></td>
</tr>
添加 问号后,页面正常访问:
============= 分割线 =============
特别补充,不要踩坑
分割线以上对赋值时的空值做了处理,页面访问不再报错,但是极有可能导致接口数据无法正常读取.
特 做如下更新:
@GetMapping
public ModelAndView list(Model model){
// 获取用户列表
model.addAttribute("userList",userRepository.listUsers());
// 设置页面标题
model.addAttribute("title","用户管理");
return new ModelAndView("users/list","uerModel",model);
}
针对以上代码块,高版本 Thymeleaf 中,可直接使用 userModel、userlist、title 三个变量。
低版本需要 userModel.userlist 才能取到 userlist 的值,再高版本这样处理反而会报错.
Thymeleaf 前端代码更新如下:
<!-- 列表为空时 给出提示 -->
<tr th:if="${userList.size()} eq 0">
<td colspan="3">没有用户信息!</td>
</tr>
<tr th:each="user:${userList}">
<td th:text="${user.id}"></td>
<td th:text="${user.email}"></td>
<td th:text="${user.name}"></td>
</tr>
这样可完美解决问题。。。。