星空网 > 软件开发 > Java

Velocity CheckingForNull

Q: I want to check for null, something like this:

#if ($car.fuel == null)

A: There are several approaches. Select the one most suitable depending on what you really want to do. 

Approach 1: Use the fact that null is evaluated as a false conditional. (cf. http://velocity.apache.org/engine/devel/user-guide.html#Conditionals)

#if( ! $car.fuel )
  • Note: The conditional will also pass if the result of $car.fuel is the boolean false. What this approach is actually checking is whether the reference is null or false.

 

Approach 2: Use the fact that null is evaluated as an empty string in quiet references. (cf. http://velocity.apache.org/engine/devel/user-guide.html#quietreferencenotation)

#if( "$!car.fuel" == "" )
  • Note: The conditional will also pass if the result of $car.fuel is an empty String. What this approach is actually checking is whether the reference is null or empty.

BTW, just checking for empty can be achieved by:

#if( "$car.fuel" == "" )

 

Approach 3: Combine Approach 1 and 2. This will check for null and null only.

#if ((! $car.fuel) && ("$!car.fuel" == ""))
  • Note: The logic underlying here is that: "(null or false) and (null or > empty-string)" => if true, must be null. This is true because "false and empty-string and not null" is never true. IMHO, this makes the template too complicated to read.

 

Approach 4: Use a Tool that can check for null (NullTool,ViewNullTool).

#if( $null.isNull($car.fuel) )
  • Note: Of course, NullTool must be in the Context as $null in this case.

 

Approach 5: Don't check for null directly, use a self-explaining method.

#if( $car.fuelEmpty )
  • Note: This is my (Shinobu Kawai's) recommended solution. You have to implement the method, but it makes the template so easy-to-read.

 

public boolean isFuelEmpty(){ // return true if fuel is empty.}

Approach 6: Use a custom directive. cf. IfNullDirective, IfNotNullDirective

#ifnull( $car.fuel )#ifnotnull( $car.fuel )
  • Note: You will have to register the directive in your velocity.properties.

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



原标题:Velocity CheckingForNull

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

数魔跨境:https://www.ikjzd.com/w/1425
亚易知识产权_深圳市亚易知识产权代理有限公司:https://www.ikjzd.com/w/1426
转口贸易:https://www.ikjzd.com/w/1427
亚马逊The Drop:https://www.ikjzd.com/w/1428
海外仓_百飞科海外仓:https://www.ikjzd.com/w/1429
coupons:https://www.ikjzd.com/w/143
加拿大本地账户开立是否需要加拿大身份? :https://www.xlkjsw.com/news/92266.html
亚龙湾有什么景点必看 亚龙湾有哪些景点:https://www.vstour.cn/a/408228.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流