(Spring) th:with 基于条件

And*_*tte 5 java spring spring-mvc thymeleaf spring-boot

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

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

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

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

我究竟做错了什么?

事实上,我想在 myField 不存在时设置valueID为。{myField.value.getId()}null

Nik*_*las 3

使用?运算符应该足够了:

<span th:with="valueID=${myField?.value.getId()}">
Run Code Online (Sandbox Code Playgroud)

getter 方法可以省略:

<span th:with="valueID=${myField?.value.id}">
Run Code Online (Sandbox Code Playgroud)

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