2

I'm using thymeleaf together with spring and there's an error when parsing the following html segment

<tbody>
    <tr th:each="item:${systemUsers}">
        <td th:text="${item.username}"/>
        <td th:text="${item.fullName}"/>
        <td th:text="${item.mobile}"/>
        <td th:text="${item.enabled}"/>
        <td th:text="${item.manGrade}"/>
        <td th:text="${item.branch.branchName}"/>
        <td>
            <a th:href="@{/users/detail/{id}(id=${item.id})}" class="btn btn-info">Details</a>
        </td>
        <td>
            <a th:href="@{/users/edit/{id}(id=${item.id})}" class="btn btn-danger">Edit</a>
        </td>
    </tr>
</tbody>

The entity systemuser contains one property branch, which is also an entity and contains one property branchName. But when rendering the html, there's an error

2016-07-14 10:07:31.114 ERROR 8088 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "systemusers/list": Exception evaluating SpringEL expression: "item.branch.branchName" (systemusers/list:38)
2016-07-14 10:07:31.116 ERROR 8088 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/crpms] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "item.branch.branchName" (systemusers/list:38)] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'branchName' cannot be found on null

What is wrong? Am I missing something in configuration of Thymeleaf?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
lupper
  • 21
  • 1
  • 1
  • 4

2 Answers2

2

This error means that in item.branch.branchName object branch is null, so Thymeleaf can't render it. Add ternary operator for processing this case :

<tbody>
  ...
  <td th:text="${item.branch == null ? '' : item.branch.branchName}"/>
  ...
</tbody>
sanluck
  • 1,544
  • 1
  • 12
  • 22
1

In addition to @sanluck answer, I think it's better to check if it is not null, as it is faster and more reliable in my opinion:

<tbody>
  ...
  <td th:text="${item.branch != null ? item.branch.branchName : 'NOT FOUND'}"/>
  ...
</tbody>
m.aibin
  • 3,528
  • 4
  • 28
  • 47