【问题标题】:(Spring) th:with based on a condition(Spring) th:with 基于一个条件
【发布时间】:2020-08-05 23:18:18
【问题描述】:

我想根据条件在百里香中分配一个变量:

<span th:with="valueID=${${myField != null} ? {myField.value.getId()}}">

这不起作用,并给了我一个例外:

"Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: `"${myField == null} ? {myField.value.getId()}"`"

我做错了什么?

实际上我想在 myField 不是 null 时将 valueID 设置为 {myField.value.getId()}

【问题讨论】:

  • 这对我有用——不是 Spring 方言,只是标准 Thymeleaf 方言(Spring 可能有另一种方法):&lt;span th:with="valueID=${myField != null} ? ${myField.value.id} "&gt;。它假设您有valueid 的相关吸气剂。当myField 为空时,你想发生什么?您也可以使用完整的 ? : 运算符。

标签: java spring spring-boot spring-mvc thymeleaf


【解决方案1】:

使用? 操作符就足够了:

<span th:with="valueID=${myField?.value.getId()}">

getter 方法可以省略:

<span th:with="valueID=${myField?.value.id}">

但是,代码仍然不是 null 安全的,因为 value 也可以是 null

【讨论】:

  • 看起来很有趣,但我得到: 原因:org.thymeleaf.exceptions.TemplateProcessingException:评估 SpringEL 表达式的异常:“myField?.value.getId()”(模板:“base.entity.generic /GenericTableWithIdListing" - 第 122 行,第 31 列) ... 原因:org.springframework.expression.spel.SpelEvaluationException:EL1011E:方法调用:尝试在空上下文对象上调用方法 getId() ...我必须我想改天再检查一下,谢谢你直到现在:)
  • 正如我告诉你的,value 可能为 null,这可能是造成这种情况的原因。你可能想要:&lt;span th:with="valueID=${myField?.value?.id}"&gt;
猜你喜欢
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多