2

我将thymeleaf与spring一起使用,解析以下html段时出现错误

<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>

实体systemuser包含一个属性branch,它也是一个实体并包含一个属性branchName。但是在渲染html时,出现错误

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

怎么了?我在 Thymeleaf 的配置中遗漏了什么吗?

4

2 回答 2

2

此错误表示 in item.branch.branchNameobjectbranch为 null,因此 Thymeleaf 无法渲染它。添加三元运算符来处理这种情况:

<tbody>
  ...
  <td th:text="${item.branch == null ? '' : item.branch.branchName}"/>
  ...
</tbody>
于 2016-07-14T02:38:08.653 回答
1

除了@sanluck 答案,我认为最好检查它是否不为空,因为我认为它更快更可靠:

<tbody>
  ...
  <td th:text="${item.branch != null ? item.branch.branchName : 'NOT FOUND'}"/>
  ...
</tbody>
于 2016-07-14T02:40:10.957 回答