首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Thymeleaf 遍歷 List 報錯「Property not found on null」解決方案

     編輯:程式設計疑難解答

錯誤現象

org.springframework.expression.spel.SpelEvaluationException: 
EL1007E:(pos 0): Property or field 'appointId' cannot be found on null

後端 Controller 正常將 List<Appoint> 放入 Model (model.addAttribute("appoints", results)),實體類有 appointId 等屬性及 Getter,但 Thymeleaf 模板遍歷時提示屬性找不到,且 IDEA 提示 Getter 未被使用、循環變量 appoint 無法解析。

根本原因

HTML 表格結構不合法:<tr> 直接包裹 <td> 之外缺少 <tr> 標籤,導致瀏覽器解析 DOM 時結構錯亂,Thymeleaf 引擎在解析屬性表達式時上下文異常,誤判對象為 null。

錯誤示例

<table>
  <th>ID</th><th>姓名</th>
  <tr th:each="appoint : ${appoints}">
    <td>[[${appoint.appointId}]]</td>
    <td>[[${appoint.name}]]</td>
  </tr>
</table>

上述缺少外層 <tbody> 或 <tr> 包裹表頭,但更常見的是 th:each 寫在 <tr> 上卻漏寫了 <tbody>,或 <td> 不在 <tr> 內。

正確結構

<table>
  <thead>
    <tr><th>ID</th><th>姓名</th></tr>
  </thead>
  <tbody>
    <tr th:each="appoint : ${appoints}">
      <td th:text="${appoint.appointId}"></td>
      <td th:text="${appoint.name}"></td>
    </tr>
  </tbody>
</table>

檢查清單

  • ✅ th:each 寫在 <tr> 標籤上。
  • ✅ <tr> 位於 <tbody> 內(或直接在 <table> 內)。
  • ✅ 每個 <td> 都在 <tr> 內部。
  • ✅ 實體類 Getter 方法為 public,命名符合 JavaBean 規範(getAppointId)。
  • ✅ Controller 傳遞的 Model 屬性名與模板 ${appoints} 一致。

總結

Thymeleaf 「Property not found on null」往往非後端數據問題,而是模板 HTML 結構不合法導致解析上下文異常。補全 <tbody>、確保 <tr>/<td> 嵌套正確即可解決。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved