--- title: Velocity 快速入门 date: 2022-02-17 22:34:30 order: 03 categories: - Java - 工具 - 模板引擎 tags: - Java - 模板引擎 - Velocity permalink: /pages/4f9c9f68/ --- # Velocity 快速入门 **Velocity (简称 VTL)是一个基于 Java 的模版引擎**。它允许 web 页面设计者引用 JAVA 代码预定义的方法。Web 设计者可以根据 MVC 模式和 JAVA 程序员并行工作,这意味着 Web 设计者可以单独专注于设计良好的站点,而程序员则可单独专注于编写底层代码。Velocity 将 Java 代码从 web 页面中分离出来,使站点在长时间运行后仍然具有很好的可维护性,并提供了一个除 JSP 和 PHP 之外的可行的被选方案。 ## 注释 单行注释以##开始,并在本行结束。 ```velocity ## This is a single line comment. ``` 多行注释,以 `#` 开始并以 `#` 结束可以处理这种情况。 ```velocity #* Thus begins a multi-line comment. Online visitors won't see this text because the Velocity Templating Engine will ignore it. *# ``` 注释块 ,可以用来存储诸如文档作者、版本信息等。 ```velocity #** This is a VTL comment block and may be used to store such information as the document author and versioning information: @author @version 5 *# ``` ## 引用 VTL 中有三种类型的引用:变量,属性和方法。 ### 变量 变量(Variables)的简略标记是有一个前导 `$` 字符后跟一个 VTL 标识符(Identifier.)组成。一个 VTL 标识符必须以一个字母开始(a .. z 或 A .. Z)。 剩下的字符将由以下类型的字符组成: - 字母 (a .. z, A .. Z) - 数字 (0 .. 9) - 连字符("-") - 下划线 ("\_") 示例:有效变量 ```velocity ## 有效变量变量名 $foo $mudSlinger $mud-slinger $mud_slinger $mudSlinger1 ## 给变量赋值 #set( $foo = "bar" ) ``` ### 属性 VTL 引用的第二种元素是属性,而属性具有独特的格式。属性的简略标记识前导符 `$` 后跟一个 VTL 标识符,在后跟一个点号(".")最后又是一个 VTL 标识符。 示例:有效属性 ```velocity $customer.Address $purchase.Total ``` ### 方法 方法在 JAVA 代码中定义,并作一些有用的事情,比如运行一个计算器或者作出一个决定。方法是实际上也是引用,由前导符 `$` 后跟一个 VTL 标识符,后跟一个 VTL 方法体(Method Body)。 VTL 方法体由一个 VTL 标识符后跟一个左括号,再跟可选的参数列表,最后是右括号。 示例:有效方法 ```velocity $customer.getAddress() $purchase.getTotal() $page.setTitle( "My Home Page" ) $person.setAttributes( ["Strange", "Weird", "Excited"] ) ``` ## 赋值 `#set` 指令用来为引用设置相应的值。值可以被值派给变量引用或者是属性引用,而且赋值要在括号里括起来。 ```velocity #set( $monkey = $bill ) ## variable reference #set( $monkey.Friend = "monica" ) ## string literal #set( $monkey.Blame = $whitehouse.Leak ) ## property reference #set( $monkey.Plan = $spindoctor.weave($web) ) ## method reference #set( $monkey.Number = 123 ) ##number literal #set( $monkey.Say = ["Not", $my, "fault"] ) ## ArrayList ``` ## 字符串 使用 `#set` 指令时,括在双引号中的字面字符串将解析和重新解释 。 然而,当字面字符串括在单引号中时,不被解析: 示例: ```velocity #set( $foo = "bar" ) $foo #set( $blargh = '$foo' ) $blargh ``` 输出: ```velocity Bar $foo ``` ## 条件 VTL 使用 `#If`、`#elseif`、`#else` 指令做条件语句控制。 示例: ```velocity #if( $foo < 10 ) Go North #elseif( $foo == 10 ) Go East #elseif( $bar == 6 ) Go South #else Go West #end ``` ## 逻辑 VTL 支持与(`&&`)、或(`||`)、非(`!`)逻辑判断。 示例: ```velocity #if( $foo && $bar ) This AND that #end #if( $foo || $bar ) This or That #end #if( !$foo ) NOT that #end ``` ## 循环 VTL 通过 `#foreach` 支持循环 ```velocity
| Superior |
| Michigan |
| Huron |
| Erie |
| Ontario |