1. velocity 是什么?
Velocity 是一个基于Java的模版引擎,它提供模版语言用于引用Java代码定义的对象。
2. Velocity 能做什么?
Velocity能创建HTML页面,并预留占位符。(最基本用途)
Velocity能基于模板生成Java,SQL源代码。(没见过)
自动生成电子邮件。(没见过)
读取XML,并转换成需要的文档格式,通常是HTML。(没见过)
3. Velocity示例
Velocity 注解
单行 ##
多行 #* *#
代码块注释(信息) ##* *#
Velocity 变量
定义:
#set( $foo = "Velocity" )
使用:
$foo
${foo}Velocity 集合
#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
Velocity 条件判断
#if( $foo < 10 )
Go North
#elseif( $foo == 10 )
Go East
#else
Go West
#endVelocity 循环
#foreach( $customer in $customerList )
#if( $foreach.count > 5 )
#break
#end
$customer.Name
#endVelocity 引用文件
#include( "one.vm" ) one.vm 不解析。 #parse( "me.vm" ) me.vm 解析。
Velocity 定义代码块
#define( $block ) Hello $who #end #set( $who = 'World!' ) $block
Velocity 宏调用
无参
#macro( d )#end #d()
单参
#macro( d )#end #@d()Hello#end $!bodyContent
任意参数
定义
#macro( tablerows $color $somelist )
#foreach( $something in $somelist )
$something
#end
#end调用
#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] ) #set( $color = "blue" )
输出
| Superior |
| Michigan |
| Huron |
| Erie |
| Ontario |
Velocity 填坑
1. 各种写法
$foo
## is the same as
${foo}
$foo.getBar()
## is the same as
$foo.Bar$data.setUser("jon")
## is the same as
#set( $data.User = "jon" )
$data.getRequest().getServerName()
## is the same as
$data.Request.ServerName## is the same as
${data.Request.ServerName}2. Velocity 变量未定义
使用 $!,例
$!foo
当 foo 未定义,输出空白字符串。
3. Velocity 调用顺序
Velocity中$customer.address,调用顺序:
getaddress()getAddress()get("address")isAddress()4. #if ($foo)
两种情况都返回true:
(1)$foo是一个 boolean 类型,且为 true。
(2)$foo不是 0,也不是 null。
5. #if ($foo == $bar)
因为Velocity变量最终都作为字符串输出,所以Velocity会自动调用 .toString() 将变量转换成字符串。
所以,$foo 和 $bar 都当成字符串进行比较。即使Java代码中类型不同,也有可能返回true。
Velocity 严格模式
Velocity 1.6引入严格引用模式,通过设置Velocity配置属性“runtime.references.strict”为true激活。
当遇到没有定义或者存在歧义的情况Velocity将抛出异常。
希望这篇文章对你有帮助。by iamtjcn










