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, i.e.
<td th:text="${user.department?.name}"></td>
This will check first whether department is null. See Spring EL's Safe Navigation Operator