velocity模板引擎学习(1)

时间:2022-04-23
本文章向大家介绍velocity模板引擎学习(1),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

velocityfreemaker、jstl并称为java web开发三大标签技术,而且velocity在codeplex上还有.net的移植版本NVelocity,(注:castle团队在github上也维护了一个版本)对于使用异构技术的团队(即要搞.NET又要搞JAVA),总是希望找一种通用的技术,兼容所有技术平台,以便降低学习成本,无疑velocity是一种值得考虑的选择。

一、与strtus2的集成

 1         <dependency>
 2             <groupId>org.apache.velocity</groupId>
 3             <artifactId>velocity</artifactId>
 4             <version>1.7</version>
 5         </dependency>
 6 
 7         <dependency>
 8             <groupId>org.apache.velocity</groupId>
 9             <artifactId>velocity-tools</artifactId>
10             <version>2.0</version>
11         </dependency>

pom.xml中加入这二项即可,其它不用刻意配置。struts2同时支持jstl(.jsp)、velocity(.vm)、freemaker(.ftl)三种模板。

二、定义变量

1   #set($awbpre='112')
2   #set($awbno='89089011')
3   #set($airwayBillNo=$awbpre+' - '+$awbno)
4   $awbpre - $awbno <br/>
5   $airwayBillNo

velocity的语法符号大概分二类,一类用#开头,代表控制符号,#set表示定义变量,另一类用$开头,通常用于显示变量,上面的示例定义了三个变量: awbpre 值为'112',awbno值为'89089011',airwayBillNo值为 '112 - 89089011'

第4,5二行输出内容

三、遍历数组

1   #set($list = ["CTU", "SHA", "LAX"])
2   #foreach ($item in $list)
3      $velocityCount . $item <br/>
4   #end

解释:定义了一个数组,然后遍历输出,其中velocityCount为索引变量

四、遍历HashTable

1   #foreach($key in $table.keySet())
2     $key -> $table.get($key)<br/>
3   #end

五、判断是否为空

1       #if($null.isNull($orderList.orders) || $orderList.orders.size()==0)
2           订单列表为空
3       #else
4           订单列表:<br/>
5           #foreach ($order in $orderList.orders)
6               $velocityCount: $order.id / $order.clientName / $order.amount / $order.createTime<br/>
7           #end
8       #end

上面是判断集合是否为空的,如果判断单个对象是否为空,参考下面这样:

 1     #if($(orderDto))
 2         订单对象有值
 3     #else
 4         订单对象为空
 5     #end
 6 
 7     #if(!$(orderDto))
 8         订单对象为空
 9     #else
10         订单对象有值
11     #end

六、宏示例

宏可以理解为“函数”,定义一个宏即相当于定义一个子函数,调用宏,即为调用子函数

 1     #macro(renderOrderList $orders)
 2         <table border="1">
 3           <tr>
 4               <th>Id</th>
 5               <th>ClientName</th>
 6               <th>Amount</th>
 7               <th>CreateTime</th>
 8           </tr>
 9           #foreach($o in $orders)
10             <tr><td>$o.id</td><td>$o.clientName</td><td>$o.amount</td><td>$o.createTime</td></tr>
11           #end
12         </table>
13     #end
14 
15     #renderOrderList($orderList.orders)

七、数值、日期格式化

1     $order.createTime<br/>
2     $date.year - $date.month - $date.day <br/>
3     $date.format('yyyy-MM-dd HH:mm:ss',$order.createTime,$locale)<br/>  
4     $date.format('MMMdd',$order.createTime,$locale)<br/>    
5     $convert.toLocale("en_US") <br/>
6     $date.format('MMM,dd',$order.createTime,$convert.toLocale("en_US"))<br/>
7     $date.format('yyyy-MM-dd',$order.createTime,$locale)<br/>
8     $order.amount<br/>
9     $number.format('0.00',$order.amount)<br/>
NumberTool中还有货币格式化的功能:$number.format("currency", $agentBillDto.feeTotal)

要使用格式化功能,需要加一点配置,struts.xml文件中加一行

<constant name="struts.velocity.toolboxlocation" value="WEB-INF/classes/toolbox.xml" />

然后在toolbox.xml中,参考下面的内容:

 1 <?xml version="1.0" encoding="UTF-8"?> 
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
 4     "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
 5 <toolbox>
 6     <tool>
 7         <key>number</key>
 8         <scope>application</scope>
 9         <class>org.apache.velocity.tools.generic.NumberTool</class>
10     </tool>
11     <tool>
12         <key>date</key>
13         <scope>application</scope>
14         <class>org.apache.velocity.tools.generic.DateTool</class>
15     </tool>
16     <tool>
17         <key>text</key>
18         <scope>request</scope>
19         <class>org.apache.velocity.tools.struts.MessageTool</class>
20     </tool>
21     <tool>
22         <key>convert</key>
23         <scope>application</scope>
24         <class>org.apache.velocity.tools.generic.ConversionTool</class>
25     </tool>
26 </toolbox>

这些XXXTool其实是一个很好的例子,因为velocity的vm文件里不能直接写java代码,如果我们想扩展一些常用方法,可以将一些常用方法写成XXXTool工具类,然后在toolbox中注册即可。

八、国际化

1  当前语言环境:$locale <br/>   
2  #stext("name=%{getText('appName')}")

虽然Velocity-Tools 2.0中提供了MessageTool,但是我一直没尝试成功,只能借助struts2本身的标签来处理了。struts2中首先得定义国际化资源文件的BaseName

1 <constant name="struts.custom.i18n.resources" value="message"></constant>

然后在classPath目录下,放二个文件message_zh_CN.properties、message_en_US.properties,里面放一个appName=XXX的内容,用#stext就能取到国际化的内容了

九、使用struts2标签

虽然有了velocity基本上可以告别struts2的那一堆tags,但是如果怀念struts2里的标签,也可以继续使用,方法:以“#s”开头就行了,参考下面的示例:

1 #stextarea ("label=Biography" "name=bio" "cols=20" "rows=3") <br/>
2 #sselect("label=Favourite Color" "list={'Red', 'Blue', 'Green'}" "name=favouriteColor" "emptyOption=true" "headerKey=None" "headerValue=None")    <br/> 

十、内建对象

1 $request<br/>
2 name = $request.getParameter("name")<br/>
3 $session<br/>

Velocity可以直接使用struts2的很多内置对象,比如Request、Session、Response,上面的示例演示了如何获取 url请求参数

十一、include、parse实现布局模块化

每个页面,通常会有一些公用的头、尾,可以用include或parse来包括其它vm文件(或txt/html文件),这二个的区别在于include只是简单的把其它文件导入进来,不会执行任何vm语法的解析。而parse导入其它vm文件时,如果其它vm文件里有一些指令,比如定义变量,定义宏之类,parse会解析执行。

1 #parse("template/header.vm")
2 #include("template/footer.vm")

关于加载的路径,这里要重点解释一下,官方文档上也讲得不清不楚,Velocity支持二种路径加载机制,按classPath或按filePath,默认是按classPath路径加载,即:只要被包含的.vm文件在/WEB-INF/classes目录下即可。上面的示例,将在/WEB-INF/classes/template目录下,搜索header.vm、footer.vm这二个文件,如果找到就加载,否则出错。

最后谈下IDE以.vm的可视化支持问题,目前最新的eclipse上,暂无好用的插件(googlecode上的插件大多已经没人维护了,与最新的eclipse不兼容),建议使用IntelliJ Idea,它对vm的可视化支持程度较好。

更详细的用法,请参考下面官司文档:

Velocity Engine 用户指南

Velocity Engine 开发人员指南

Velocity Tools 用法概述