【问题标题】:Thymeleaf th:if with null errorThymeleaf th:如果有空错误
【发布时间】:2017-01-22 13:00:04
【问题描述】:

我正在尝试使用 Spring Boot 中的一些数据填充 thymeleaf 模板。 我想做的是这个

<tr th:if="${group.organization}">
    <td class="col_title"><b>Organization:</b></td>
    <td class="organization-field-content" th:text="${group.organization}"></td>
</tr>

我已经尝试了这里提出的两种解决方案: Thymeleaf: show text if the attribute and property exists 并且按照 thymeleaf 的渲染顺序,由于group.organization 为空,所以不应显示整个内部的tds。

仍然存在问题,因为 Thymeleaf 抱怨说

Servlet.service() for servlet [dispatcherServlet] in context with path [] 
threw exception [Request processing failed; nested exception is 
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating 
SpringEL expression: "group.organization" (group)] with root cause
java.lang.NullPointerException: null

我不明白为什么会这样,因为组对象存在,只是组织为空

【问题讨论】:

  • organizationboolean 属性吗?如果没有,这样做更有意义:&lt;tr th:if="${group != null &amp;&amp; group.organization != null}"&gt; &lt;td class="col_title"&gt;&lt;b&gt;Organization:&lt;/b&gt;&lt;/td&gt; &lt;td class="organization-field-content" th:text="${group.organization}"&gt;&lt;/td&gt; &lt;/tr&gt;

标签: java spring-boot thymeleaf


【解决方案1】:

感谢大家的回复,原来问题出在其他地方。

所有建议的解决方案仍然存在相同的问题,这是因为 Group Spring-data 模型中的一种方法。 实际上,空指针异常来自 getOrganization 方法,它没有正确序列化 null 值。

也许这可以帮助将来的其他人

【讨论】:

    【解决方案2】:

    在显示 div 之前,可以尝试以下方法来检查组和组织是否不为空。

    <tr th:if="${group != null && group.organization != null}">
        <td class="col_title"><b>Organization:</b></td>
        <td class="organization-field-content" th:text="${group.organization}"></td>
    </tr>
    

    【讨论】:

      【解决方案3】:

      您可以通过将其转储到类似&lt;span th:utext="${group}" /&gt; 的跨度中来确认您的组对象是否真的不为空

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-17
        • 1970-01-01
        • 1970-01-01
        • 2018-04-26
        • 1970-01-01
        • 2018-05-06
        • 2015-11-19
        相关资源
        最近更新 更多