简体   繁体   English

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

[英]How to access inner objects in Thymeleaf?

I am trying to Iterate a List if User s using thymeleaf,如果User使用百里香叶,我正在尝试迭代一个列表,

My User object is like this我的User对象是这样的

public class User implements java.io.Serializable {

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

and department object is like this部门对象是这样的

public class Department implements java.io.Serializable {

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

in thymeleaf I do this在百里香中,我这样做

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

and I am getting this error我收到这个错误

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

if I use only user.email , there is no issues.如果我只使用user.email ,则没有问题。

So how to access inner objects in in Thymeleaf EL?那么如何访问 Thymeleaf EL 中的内部对象呢? (In my case user.department.name ) (在我的情况下user.department.name

You are accessing it correctly, but you will get an exception if the department on the user is null.您正在正确访问它,但如果用户的部门为空,您将收到异常。

What you can do is use null safe dereferencing using the '?'您可以做的是使用“?”使用空安全解除引用。 operator, ie运算符,即

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

This will check first whether department is null.这将首先检查部门是否为空。 See Spring EL's Safe Navigation Operator查看 Spring EL 的安全导航操作符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM