【问题标题】:Checking if a specific field exists on an object in Thymeleaf page检查 Thymeleaf 页面中的对象上是否存在特定字段
【发布时间】:2020-08-03 02:00:31
【问题描述】:
<th:block th:each="item : ${mclist}" >
           <option th:if="${item.id}" th:value="${item.id}" th:text="${item}"></option>
           <option th:if="${item.id == null}" th:value="${item}" th:text="${item}"></option>
 </th:block>

对象“item”可以是任何实体。因此,它可能包含也可能不包含“id”字段。当实体不包含“id”字段时,此处显示的代码会出现以下错误。

org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'id' cannot be found on object of type 'java.lang.String' - maybe not public or not valid?

是否可以在提取值之前检查 'item' 对象中是否存在 id 字段?

【问题讨论】:

  • 我认为 Thymeleaf 中没有任何原生支持来检查对象上是否存在字段。您将要做的最好的事情是编写自己的辅助方法,如果对象具有 id 字段,则使用反射返回 truefalse,并在 Thymeleaf 中使用它。虽然这是一些非常奇怪的设计......

标签: java spring spring-mvc jsp thymeleaf


【解决方案1】:

尝试使用“?”操作员。像这样的:

<div th:if="${item?.id}">
    <option th:value="${item.id}" th:text="${item}"></option>
</div>

【讨论】:

  • 这不会给你某种形式的在对象上找不到属性或字段'id'错误吗?我们不检查该字段的值是否为空。我们要检查对象上是否存在字段存在
  • 感谢@user3088166。我试过 "${item?.id}" 方法。仍然有同样的错误。
猜你喜欢
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
  • 2015-02-27
相关资源
最近更新 更多