现在的位置: 首页 > 综合 > 正文

velocity 判空

2014年02月17日 ⁄ 综合 ⁄ 共 988字 ⁄ 字号 评论关闭

相信这个问题是很多使用Velocity的朋友所经常碰到的,大家可能非常期望下面这样的代码能够运行:

    #if($foo == null) 
       ...
    #end

但结果会是报错。页面直接显示不出来。

而如果不进行判空,即便是空它还不会报错,只是把该变量的表达式直接显示在页面。

比如

 <td align="right">$numberTool.format($CURRENCY, $foo)</td>

当$healthAndWelfare.ISpLifeAmt 为null的时候,会显示$numberTool.format($CURRENCY, $foo)

断是否为null有下面几种方法:

1. #if (! $foo) 判断$foo为空,判断非空为 #if ($foo)

2. 使用null工具判断

    #if($null.isNull($foo))

    注意这种方式特别有用,尤其你在需要这个判断作为一个判断字句时,比如我要你判断一个集合为null或为空时只能使用这种方式了:

    $if ($null.isNull($mycoll) || $mycoll.size()==0)

e.g:

 #if($null.isNull($foo))
  <td align="right">$numberTool.format($CURRENCY, $foo)</td>
  #else
  <td align="right">$numberTool.format($CURRENCY, 0.00)</td>
  #end

3.使用 #ifnull() 或 #ifnotnull()

    #ifnull ($foo)

    要使用这个特性必须在velocity.properties文件中加入:

userdirective = org.apache.velocity.tools.generic.directive.Ifnull
userdirective = org.apache.velocity.tools.generic.directive.Ifnotnull

更详细的介绍请参考:

http://wiki.apache.org/velocity/VelocityNullSupport
http://wiki.apache.org/velocity/CheckingForNull

转自 http://feiyan35488.iteye.com/blog/767121

抱歉!评论已关闭.