如何在FreeMarker中正确校验布尔值?遇方法序列类型错误
FreeMarker布尔值校验问题解决方案
问题场景
尝试编写FreeMarker条件判断逻辑,代码如下:
<#if documentData.isOtherInsurance> <p>✔ Да</p> <#else> <p>✘Нет </p></#if>
报错信息
执行后出现类型不匹配错误:
For "#if" condition: Expected a boolean, but this has evaluated to a method+sequence (wrapper: f.e.b.SimpleMethodModel): ==> documentData.isOtherInsurance!false [in template "InsuranceNotification" at line 1, column 1445] ---- Tip: Maybe using obj.something instead of obj.isSomething will yield the desired value. ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: #if documentData.isOtherInsurance!false [in template "InsuranceNotification" at line 1, column 1440] ----
错误尝试及新问题
尝试修改为以下代码(错误使用插值语法):
<#if ${documentData.isOtherInsurance>} <p>✔ Да</p> ...
触发语法错误:
Syntax error in template "InsuranceNotification" in line 1, column 1445: You can't use ${...} (an interpolation) here as you are already in FreeMarker-expression-mode. Thus, instead of ${myExpression}, just write myExpression. (${...} is only used where otherwise static text is expected, i.e., outside FreeMarker tags and interpolations, or inside string literals.)
正确解决方法
- 改用属性名访问布尔值:
根据报错提示,直接使用属性名而非isXXX方法名来获取值。FreeMarker会自动匹配Java对象中对应的isOtherInsurance()或getOtherInsurance()方法,返回布尔类型结果:<#if documentData.otherInsurance!false> <p>✔ Да</p> <#else> <p>✘Нет</p> </#if> - 避免在表达式模式中使用插值:
#if标签内部已经处于表达式解析模式,直接写变量名即可,不需要包裹${}。 - 空值安全处理:
使用!false语法,确保当otherInsurance为null时,默认取值为false,避免空值导致的运行错误。
内容的提问来源于stack exchange,提问作者Roman Prikhodko
相关产品推荐
相关产品推荐

