Spring Boot Thymeleaf 报错:Whitelabel Error Page

今天练习 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>

这样可完美解决问题。。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值