2017年2月27日星期一

属性Property与方法Methods

VTL(Velocity Template Language)输出变量时可以通过属性或Java方法来实现。

由$定义值+"."+另一个定义值,如:
$customer.address
有两个含义。1、查找customer的散列表,并返回名为address关联的值;2、是$customer.getAddress()的简写。当请求发生时,Velocity将判断哪种是有意义的并返回对应的值。

在使用Java方法来实现时,还可以传递参数。
$customer.setName("Velocity")

虽然$customer.address和$customer.getAddress有完全相同的效果,但通常被建议使用属性来实现。它们之间的差别在于可以为方法指定参数列表。

从Velocity 1.6开始,若数组为固定长度的列表,则可以调用java.util.list方法。如:

  • $myArray.isEmpty()
  • $myArray.size()
  • $myArray.get(2)
  • $myArray.set(1, 'Velocity')

Velocity 1.6之后也支持vararg方法。

Velocity分析属性的规则

对于以小写字母开头的属性,如:$customer.address。查找顺序为:

  1. getaddress()
  2. getAddress()
  3. get("address")
  4. isAddress()

而若以大写开头的属性,如:$customer.Address。查找顺序为:

  1. getAddress()
  2. getaddress()
  3. get("Address")
  4. isAddress()

故而建议在定义属性时不要依赖于大小写来区别属性。

没有评论:

发表评论