org.springframework.expression.spel.SpelEvaluationException - Property or field cannot be found on null

lupper picture lupper · Jul 14, 2016 · Viewed 11.7k times · Source

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?

Answer

sanluck picture sanluck · Jul 14, 2016

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>