`
esteem
  • 浏览: 154050 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Velocity中如何判断null

    博客分类:
  • J2EE
阅读更多

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

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

实际上这段代码会报错。这是因为Velocity中对null的支持比较特别。总统上说,判断是否为null有下面几种方法:

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

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

    #ifnull ($foo)

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

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

3. 使用null工具判断

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

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

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

更详细的介绍请参考:

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

分享到:
评论
3 楼 lwy520 2015-09-11  
如何加载自定义的属性文件
2 楼 linyuanquan 2011-12-20  
userdirective = org.apache.velocity.tools.generic.directive.Ifnull
userdirective = org.apache.velocity.tools.generic.directive.Ifnotnull
加这两个进去报错呢,是缺包吗?如果是缺包,是缺什么包啊?网上没有这个错误的
Caused by: org.apache.velocity.exception.VelocityException: Failed to load Directive: org.apache.velocity.tools.generic.directive.ifnotnull
at org.apache.velocity.runtime.RuntimeInstance.loadDirective(RuntimeInstance.java:957)
at org.apache.velocity.runtime.RuntimeInstance.initializeDirectives(RuntimeInstance.java:889)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:252)
at org.apache.velocity.app.VelocityEngine.init(VelocityEngine.java:107)
at org.springframework.ui.velocity.VelocityEngineFactory.createVelocityEngine(VelocityEngineFactory.java:251)
at org.springframework.web.servlet.view.velocity.VelocityConfigurer.afterPropertiesSet(VelocityConfigurer.java:119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400)
... 36 more
Caused by: java.lang.ClassNotFoundException: org.apache.velocity.tools.generic.directive.ifnotnull
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at org.apache.velocity.util.ClassUtils.getClass(ClassUtils.java:77)
at org.apache.velocity.util.ClassUtils.getNewInstance(ClassUtils.java:96)
at org.apache.velocity.runtime.RuntimeInstance.loadDirective(RuntimeInstance.java:935)
... 43 more
1 楼 homepageax 2011-10-10  
#if($foo == $null)
   ...
#end

相关推荐

Global site tag (gtag.js) - Google Analytics