简体   繁体   中英

How to access inner objects in Thymeleaf?

I am trying to Iterate a List if User s using thymeleaf,

My User object is like this

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.

So how to access inner objects in in Thymeleaf EL? (In my case 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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