| Blog信息 |
|
blog名称: 日志总数:1304 评论数量:2242 留言数量:5 访问次数:7649328 建立时间:2006年5月29日 |

| |
|
[Apache(jakarta)]揭开velocity取值的秘密 软件技术
lhwork 发表于 2006/8/4 10:01:02 |
|
在利用velocity进行项目开发的过程中,很多人因为在页面取值时是使用javabean的方法还是属性争论不休。( ${obj.getName()} / ${obj.name} )今天我们就来揭开velocity取值的面纱。首先看一下Velocity的取值方式,有一个对象Customer:
500)this.width=500'>500)this.width=500'>public class Customer 500)this.width=500'>{500)this.width=500'> private String address;500)this.width=500'> private String name;500)this.width=500'>500)this.width=500'> //省略get set500)this.width=500'>500)this.width=500'>500)this.width=500'>}将这个对象放入Velocity的上下文Context中:
500)this.width=500'>context.put("customer", customer);我们在jsp页面上取这个消费者的地址和名字时就要如下这样写:
$!customer.address$!customer.name或者
$!customer.getAddress()$!customer.getName()我
们注意到使用$!customer.address属性和使用$!customer.getAddress()方法具有相同效果。当然,我们更倾向于使用
$!customer.getAddress()方法而不使用$!customer.address属性的方式,那么这两种调用方式是否有区别呢?我们来
看看下面这个例子,还是以Customer为例,不同的是这里将Customer的getAddress方法的返回值设置为定数“123”,如下: 500)this.width=500'>500)this.width=500'>public String getAddress() 500)this.width=500'>{500)this.width=500'> return "123";500)this.width=500'>}在另一class中调用该对象为其赋值并将其置入Velocity的上下文Context中:
500)this.width=500'>Customer customer = new Customer();500)this.width=500'>customer.setAddress("abc");500)this.width=500'>customer.setName("junesky.org");500)this.width=500'>500)this.width=500'>context.put("customer", customer);这
时我们在页面上利用$!customer.address属性和使用$!customer.getAddress()方法取到的值是什么?是否相同呢?考
虑到在getAddress()方法中返回的值与address属性实际的值并不相同,也许你会觉得取到的值不相同。看看结果: $!customer.address = 123$!customer.getAddress() = 123唔,是相同的。并且利用$!customer.getAddress()方法取到的值并不是我们设置的abc。再看一个例子,与上例基本相同,不同之处是将Customer的address属性名改为addressTest:
500)this.width=500'>500)this.width=500'>public class Customer 500)this.width=500'>{500)this.width=500'> private String addressTest;500)this.width=500'> private String name;500)this.width=500'>500)this.width=500'> // 注意这里方法名500)this.width=500'>500)this.width=500'> public String getAddress() 500)this.width=500'>{500)this.width=500'> return addressTest;500)this.width=500'> }500)this.width=500'>}这时,在页面上利用属性$!customer.addressTest是取不到值的,利用$!customer.address和$!customer.getAddress()方法是可以取到的。 根据以上两个例子,我们明白了Velocity的调用机制--无论使用属性还是使用方法,实际上都是调用对象的方法的。所以,在使用Velocity开发时,我们就不必为了使用属性方式还是使用方法而争论不休了。 |
|
|
回复:揭开velocity取值的秘密 软件技术
aaa(游客)发表评论于2007/7/10 21:25:58 |
|
|
回复:揭开velocity取值的秘密 软件技术
l;ll;ll(游客)发表评论于2007/3/1 10:12:20 |
|
» 1 »
|