Velocity是一种Java模版语言.
关于Velocity本身的更多信息, 请访问Velocity 网站
.
 | Velocity与FreeMarker非常相似, 它们都是可以在Servlet容器外使用的模版语言. WebWork团队更加推荐使用FreeMarker, 因为它有比Velocity更好的错误报告, 支持JSP tags, 还有其它一些细微优点. 当然, 它们都是JSP很好的替代品. |
上手
开始使用Velocity, 首先需要保证所有的依赖都已经被加入到你的工程的classpath. 其次, webwork-default.xml 中要配置好Velocity Result, 它将影射你的action和模版. 你可以使用如下的 xwork.xml 配置:
<action name="test" class="com.acme.TestAction">
<result name="success" type="velocity">test-success.vm</result>
</action>
然后在 test-success.vm 中:
<html>
<head>
<title>Hello</title>
</head>
<body>
Hello, ${name}
</body>
</html>
Where name is a property on your action. That's it! Read the rest of this document for details on how templates are loaded, variables are resolved, and tags can be used.
这里的 name 是你的action中的一个属性. 这就行了! 阅读余下的文档你将了解模版的载入, 变量如何解析, 和tags的使用.
模版载入
WebWork looks for Velocity templates in two locations (in this order):
WebWork在两个位置寻找Velocity模版( 按顺序 ):
- Web应用程序
- Class path
这个顺序使在编译好的jar包中提供模版非常方便, 同时还允许你在你的web应用程序中覆盖这些模版. 实际上, 这就是你可以覆盖WebWork默认的UI tags 和 Form Tags模版的原因.
变量解析
在Velocity中, 将从几个不同的位置查找变量, 顺序如下:
- 值栈(value stack)
- action上下文(context)
- 內建变量
注意action上下文在值栈后面. 着一位着你可以不用加上典型的前缀 (#) 引用变量, 就像你在使用JSP ww:property 标签时一样. 这很方便, 但是请小心, 有时它也有可能会给你带来小麻烦.
#wwurl "id=url "value=http://www.yahoo.com"
Click <a href="${url}">here</a>!
The built-in variables that WebWork-Velocity integration provides are:
WebWork-Velocity集成中內建的变量是:
| 名称 |
描述 |
| stack |
值栈(value stack)本身, 使用这样的语法访问${stack.findString('ognl expr')} |
| action |
最近执行的action |
| response |
HttpServletResponse |
| res |
与response相同 |
| request |
HttpServletRequest |
| req |
与request相同 |
| session |
HttpSession |
| application |
ServletContext |
| base |
request的上下文路径(context path) |
Tag支持
See the Velocity Tags documentation for information on how to use the generic Tags provided by WebWork.
察看Velocity标签文档获取更多关于如何使用WebWork提供的一般标签的内容.
提示与技巧
There are some advanced features that may be useful when building WebWork applications with Velocity.
当在WebWork应用程序中使用Velocity时, 有一些进阶的功能可能会游泳.
扩展
有时你可能希望扩展WebWork提供的Velocity支持. 最常见的原因是你希望加入你自己的标签, 就像你从WebWork內建的标签中扩展一样.
想要这样做, 写一个新的扩展自 com.opensymphony.webwork.views.velocity.VelocityManager 的类或者也可以覆盖它. 然后增加如下内容到webwork.properties:
webwork.velocity.manager.classname = com.yourcompany.YourVelocityManager
配置
你可以通过替换velocity.properties中的配置项来配置Velocity.