如何访问 Thymeleaf 中的内部对象?

How to access inner objects in Thymeleaf?

如果 User 使用 thymeleaf,我正在尝试迭代列表,

我的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

你访问的是正确的,但是如果用户的部门是空的,你会得到一个异常。

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

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

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