【问题标题】:How to access inner objects in Thymeleaf?如何访问 Thymeleaf 中的内部对象?
【发布时间】:2016-06-25 04:49:49
【问题描述】:

如果Users 使用百里香叶,我正在尝试迭代列表,

我的User对象是这样的

public class User implements java.io.Serializable {

    private Integer userId;
    private Department department;
    private String email;
    // setters and getters etc
}

部门对象是这样的

public class Department implements java.io.Serializable {

    private Integer departmentId;
    private String name;
    // setters and getters etc
}

在百里香中我这样做

<tr th:each="user : ${users}">
    <td th:text="${user.email}"></td>
    <td th:text="${user.department.name}"></td>
</tr>

我收到了这个错误

org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "user.department.name"

如果我只使用user.email,没有问题。

那么如何在 Thymeleaf EL 中访问内部对象? (在我的情况下user.department.name

【问题讨论】:

    标签: java spring el thymeleaf


    【解决方案1】:

    您正确访问它,但如果用户的部门为空,您将获得异常。

    您可以做的是使用 '?' 使用 null 安全解除引用运算符,即

    <td th:text="${user.department?.name}"></td>
    

    这将首先检查部门是否为空。见 Spring EL 的Safe Navigation Operator

    【讨论】:

    • 感谢您的输入,我会检查并更新。我认为 Department 类中存在一些问题(如果这种语法没问题)。
    • 问题出在我的查询中,部门有一个提取类型 LAZY,所以我必须在 Query 中使用 FETCH。当从百里香访问时,我会接受部门为空的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 2015-08-30
    • 2020-10-06
    相关资源
    最近更新 更多