Accessing constant values from an Apache Velocity template?

半城伤御伤魂 提交于 2019-12-06 17:40:59

问题


Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?

I would like to be able to write something like this:

#if ($a lt Long.MAX_VALUE)

but this is apparently not the right syntax.


回答1:


There are a number of ways.

1) You can put the values directly in the context.

2) You can use the FieldMethodizer to make all public static fields in a class available.

3) You can use a custom Uberspect implementation that includes public static fields in the lookup order.

4) You can use the FieldTool from VelocityTools.

I recommend 1 for a few values, 2 for a few classes, 3 for lots of classes and values, and 4 if you are already using VelocityTools and would otherwise use 1 or 2.




回答2:


Velocity can only use anything it finds in its context, after e.g.

context.put("MaxLong", Long.MAX_VALUE);

You cannot use statics, or access static members of things in Velocity's context due to the way its lookup works (see Velocity's Property lookup rules). The best thing to do is add the value you want to check against explicitly in your context.


Edit October 6 on second sight, it seems to be possible to access static members. See the velocity Developer guide - Support for "Static Classes" for more information. I have not tried this out, though.



来源:https://stackoverflow.com/questions/148601/accessing-constant-values-from-an-apache-velocity-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!