0

应用程序抛出 org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'title' cannot be found on null

我不明白为什么......这是主人调用的html片段。

<title th:fragment="title">Surveys Feed</title>
<div th:fragment="content" th:each="surv : ${allSurveys}" >
    <div id="surv-ct" style="min-width: 310px; max-width: 800px;     height:400px; margin: 0 auto">
    <script th:inline="javascript">
       /*<![CDATA[*/
           $('#surv-ct').highcharts({
               chart: {
                   type: 'bar'
               },
               title: {
                   text: [[${surv.title}]]
               },
             // ... other stuff 
    </script>
  </div>
</div>

然而,当应用程序启动时,字段标题不为空!这里我们有对象 allSurveys 的映射,它从 repo 中获取所有调查并返回一个列表。

@ModelAttribute("allSurveys")
public List<Survey> allSurveys() {
    List<Survey> surveys = new Surveys(repo.findAll()).getSurveys();
    // print surveys titles
    for (int i = 0; i < surveys.size(); i++) {
        Survey sur = surveys.get(i);
        System.out.println("Survey info: " + sur.getTitle());
    }
    return surveys;
}

作为证据,我们可以看到调查的标题打印在控制台上: 控制台输出

它们存在于数据库 调查数据库中

那么为什么它说那是空的呢?我在互联网上看到了不同的答案,但似乎没有一个可以解决我的问题。

预先感谢您的帮助。

编辑:根据建议,我尝试打印对象 ${surv}。我将内部 div 的“surv-ct”属性从 ID 更改为 class,因为它们应该很多。

<div th:fragment="content" th:each="surv : ${allSurveys}" >
    <div class="surv-ct" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto">
        <p>Object is: <span th:text=${surv}>obj</span></p>
        <!--
        <script th:inline="javascript">
           /*<![CDATA[*/

               $('.surv-ct').highcharts({
                   chart: {
                       type: 'bar'
                   },
                   // ... more code
    -->
    </div>
</div>

当我在 Mozilla 上分析代码时,结果是这样的。

    <p>Object is: <span></span></p>
    <!--
    <script th:inline="javascript">
       /*<![CDATA[*/
           $('.surv-ct').highcharts({
                // ... more code that i deleted
                // it's commented anyway
      -->

首先,只打印一个结果。其次,它没有得到任何生存对象。这就是我猜“标题”字段为空的原因。那么为什么对象为空呢?有什么建议吗?

4

1 回答 1

2

我怀疑这是因为您在使用th:include片段时正在使用。根据Thymeleaf 文档

而 th:include 会将片段的内容包含在其主机标签中,而 th:replace 将实际上用片段的主机标签替换主机标签

这意味着您th:each将被忽略 - 解释为什么您只看到打印的一个结果。

解决方案是使用th:replace,这将利用th:if。或者您可以稍微更改片段的格式,使其th:each成为片段内容的一部分。例如:

<th:block th:fragment="content">
    <div th:each="surv : ${allSurveys}">
        <div id="surv-ct" style="min-width: 310px; max-width: 800px;     height:400px; margin: 0 auto">
            <script th:inline="javascript">
               /*<![CDATA[*/
                   $('#surv-ct').highcharts({
                       chart: {
                           type: 'bar'
                       },
                       title: {
                           text: [[${surv.title}]]
                       },
                     // ... other stuff 
            </script>
        </div>
    </div>
</th:block>
于 2016-01-16T14:26:32.110 回答