2013-06-12 71 views
7

这里访问对象的公共领域是我的对象类:如何从Velocity模板

public class Address 
{ 
    public final String line1; 
    public final String town; 
    public final String postcode; 

    public Address(final String line1, final String town, final String postcode) 
    { 
     this.line1 = line1; 
     this.town = town; 
     this.postcode = postcode; 
    } 
} 

我把它添加到速度情况下是这样的:

Address theAddress = new Address("123 Fake St", "Springfield", "SP123"); 
context.put("TheAddress", theAddress); 

然而,写作模板时,下面将不会渲染地址字段(但是,当我将getter添加到Address类时它工作正常)

<Address> 
    <Line1>${TheAddress.line1}</Line1> 
    <Town>${TheAddress.town}</Town> 
    <Postcode>${TheAddress.postcode}</Postcode> 
</Address> 

是否可以从Velocity访问公共字段而不添加getters?

回答

4

不是默认情况下。您需要配置不同的Uberspect实现。

+0

你可以添加任何细节,如链接到文档如何做到这一点或为什么这是必要的? –

+2

这是必要的,因为Velocity不支持公共字段。 试试这个:http://maven-doccheck.sourceforge.net/samples/ShinobuDemo/apidocs/org/apache/velocity/tools/generic/introspection/PublicFieldUberspect.html –

+0

他们很棒,他们按照惯例实现他们的框架而不是实际的语言规则...... – evanmcdonnal

3

Velocity user guide表明这是不可能的。 Quote:

[速度]尝试不同的替代品,基于几个既定的命名约定。确切的查找顺序取决于属性名称是否以大写字母开头。对于小写的名称,如$ customer.address,序列

  1. 的getAddress()
  2. 的getAddress()
  3. GET( “地址”)
  4. isAddress()

对于像$ customer.Address大写的属性名称,它是略有不同:

  1. 的getAddress()
  2. 的getAddress()
  3. GET( “地址”)
  4. isAddress()
0

http://wiki.apache.org/velocity/VelocityFAQ

问:我如何可以访问我的对象的公共字段在我的模板?

答:目前,你有三种选择:

  • 包装你的对象有FieldMethodizer

  • 配置您VelocityEngine使用自定义uberspector像PublicFieldUberspect

  • 大堂速度-dev列表添加公共字段自省作为默认回退如果没有找到匹配的方法:)

FieldMethodizer仅适用于公共静态字段。

PublicFieldUberspect示例代码相当陈旧,它只是在不存在的字段上发生错误而失败。

而忘记在开发名单大厅。 )


与此同时,在当前velocity trunk良好的缓存UberspectPublicFieldsimplementation。不幸的是,有no active development for years,并没有发布下一个版本的计划。 你必须自己构建它并捆绑到私有存储库中。


另一个altervative是与奖金阶兼容性叉即在中央行家存储库中可用: http://maven-repository.com/artifact/com.sksamuel.scalocity/scalocity/0.9

掉落在代替通常的速度依赖性:

<dependency> 
    <groupId>com.sksamuel.scalocity</groupId> 
    <artifactId>scalocity</artifactId> 
    <version>0.9</version> 
</dependency> 

然后,只需添加到velocity.properties

runtime.introspector.uberspect = org.apache.velocity.util.introspection.UberspectPublicFields, org.apache.velocity.util.introspection.UberspectImpl 

需要说明的是UberspectImpl修补与阶性质额外的支持和需要8 MB阶罐。


最后,我刚刚从实习干线速度以下类别为自己的项目:

org.apache.velocity.runtime.parser.node.PublicFieldExecutor org.apache.velocity.runtime。 parser.node.SetPublicFieldExecutor org.apache.velocity.util.introspection.ClassFieldMap org.apache.velocity.util.introspection.Introspector org.apache.velocity.util.introspection.IntrospectorBase org.apache.velocity.util。 introspection.IntrospectorCache 个org.apache.velocity.util.introspection.IntrospectorCacheImpl org.apache.velocity.util.introspection.UberspectPublicFields

这些做工精细用速度1.7。