---
title: "velocity 语法 null"
author: "dangry"
date: "2011-01-19T11:26:49Z"
tags: []
categories: ["编程语言"]
slug: "velocity-null"
draft: false
lastmod: "2011-01-19T11:26:49Z"
id: 888536
url: "https://dangry.iteye.com/blog/888536"
---

相信这个问题是很多使用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.Ifnulluserdirective = org.apache.velocity.tools.generic.directive.Ifnotnull  
　　3. 使用null工具判断  
　　#if($null.isNull($foo))  
　　注意这种方式特别有用，尤其你在需要这个判断作为一个判断字句时，比如我要你判断一个集合为null或为空时只能使用这种方式了：  
　　$if ($null.isNull($mycoll) || $mycoll.size()==0)

详情请参考：[http://www.examda.com/ncre2/JAVA/fudao/20090114/083522201.html](http://www.examda.com/ncre2/JAVA/fudao/20090114/083522201.html)