Java (Spring)th:基于条件的

Java (Spring)th:基于条件的,java,spring,spring-boot,spring-mvc,thymeleaf,Java,Spring,Spring Boot,Spring Mvc,Thymeleaf,我想根据一个条件在thymeleaf中分配一个变量: <span th:with="valueID=${${myField != null} ? {myField.value.getId()}}"> 我做错了什么 事实上,我想在myField不为空时,使用?运算符将valueID设置为{myField.value.getId()} <span th:with="valueID=${myField?.value.getId()}"> getter方法可以省略为: &

我想根据一个条件在thymeleaf中分配一个变量:

<span th:with="valueID=${${myField != null} ? {myField.value.getId()}}">
我做错了什么


事实上,我想在myField不为空时,使用
运算符将
valueID
设置为
{myField.value.getId()}

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

getter方法可以省略为:

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


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

这对我来说很有效-不是Spring方言,只是标准的Thymeleaf方言(Spring可能有另一种方法):
。它假定您拥有
id
的相关getter。当
myField
为空时,您希望发生什么?您可以使用完整的
?:运算符。看起来也很有趣,但我得到:由以下原因引起:org.thymeleaf.exceptions.TemplateProcessingException:Exception评估SpringEL表达式:“myField?.value.getId()”(模板:“base.entity.generic/GenericTableWithIdListing”-第122行,第31列)。。。原因:org.springframework.expression.spel.SpelEvaluationException:EL1011E:方法调用:试图对空上下文对象调用方法getId()。。。我想改天再检查一下,谢谢你,直到现在:)正如我告诉你的,
值可能是空的,这可能是造成这种情况的原因。您可能需要:
<span th:with="valueID=${myField?.value.id}">