1. freemarker不支持null。
如果值为null会报错,如下:
FreeMarker template error (DEBUG mode; use RETHROW in production!): The following has evaluated to null or missing: ==> setmeal.sex [in template "mobile_setmeal.ftl" at line 41, column 42] ---- Tip: It's the step after the last dot that caused this error, not those before it. ---- Tip: If the failing expression is known to be legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing</#if>. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: #if setmeal.sex == "0" [in template "mobile_setmeal.ftl" at line 41, column 37] ---- Java stack trace (for programmers): ---- freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:131) at freemarker.core.EvalUtil.compare(EvalUtil.java:195) at freemarker.core.EvalUtil.compare(EvalUtil.java:112) at freemarker.core.ComparisonExpression.evalToBoolean(ComparisonExpression.java:64) at freemarker.core.IfBlock.accept(IfBlock.java:46) at freemarker.core.Environment.visit(Environment.java:324) at freemarker.core.MixedContent.accept(MixedContent.java:54) at freemarker.core.Environment.visitByHiddingParent(Environment.java:345)
2. 当值为null的处理
2.1 过滤不显示
在属性后面加感叹号即可过滤null和空字符串,如果name为null则为空,不会报错
示例:
Hello${name!}World
结果:HelloWorld
if和??
示例:
<#if age??> 年龄不为空:${age} <#else> 年龄为空 </#if>
结果:年龄为空
$和!
如果age为null,默认给'0'
示例:
${age!'0'}
2.2 设置默认值
示例:
<#assign info={"mobile":"13812345678",'address':'北京市昌平区'} > ${info.mobile999!"null"}
结果:null
2.3 判断是否存在值
示例:
<#assign info={"mobile":"13812345678",'address':'北京市昌平区'} > ${info.mobile999?if_exists}
结果:空,这样显示就没有问题了
2.4 忽略null值
假设前提:userName为null
${userName} error
${userName!} 空白
${userName!'tivon'} tivon
假设前提:user.name为null
${user.name},异常
${(user.name)!},显示空白
${user.name!'vakin'},若user.name不为空则显示本身的值,否则显示vakin
${user.name?default('vakin')},同上
${user.name???string('不为空','为空')},为空