Velocity入门系列

Velocity介绍

  Velocity是一个java模板引擎,经过简洁的语法能够返回动态内容给浏览器使用,本系类是基于velocity官方文档(就是照着翻译,同时对不清楚的地方进行详细讲解),其实技术文档我一直推崇看官方文档,官方文档更新及时同时讲解也很详细,可是主要是须要英语基础哈哈,下面咱们就开始velocity的学习了。html

简单的环境搭建

  在学习以前咱们先下载jar包,因为官方文档是先进行语法学习(蛋蛋的忧桑~~~~),因此这里我先进行简单的velocity搭建, 使用的是servlet,贴代码!java

  

 1 Properties p = new Properties();
 2         p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
 3         Velocity.init( p );
 4         VelocityContext context = new VelocityContext();
 5         context.put( "name", new String("Velocity") );
 6         Template template = null;
 7         StringWriter sw = new StringWriter();
 8         PrintWriter out = response.getWriter();
 9         try
10         {
11            //template = Velocity.getTemplate("cn/dota/mytemplate.vm");
12            Velocity.mergeTemplate("cn/dota/mytemplate.vm", context, out);
13         }
14         catch( ResourceNotFoundException rnfe )
15         {
16            // couldn't find the template
17         }
18         catch( ParseErrorException pee )
19         {
20           // syntax error: problem parsing the template
21         }
22         catch( MethodInvocationException mie )
23         {
24           // something invoked in the template
25           // threw an exception
26         }
27         catch( Exception e )
28         {}
View Code

这里核心的就是 1-11行,这里简单的说下velocity加载模板只有文件路径和类路径(使用velocity-tool能够增长web上下文路劲配置),第二行就是指定使用类路径, context其实就是传递参数,好了简单的环境配置好了,咱们就开始来学习le !!!!!!!!web

目录

  1. velocity template language(VTL):介绍
  2. Hello velocity world!
  3. 注释
  4. Referencesapache

  5. 格式参考标记
  6. 替代案例
  7. 指令
  8. 获得常量($符号问题)
  9. VTL:格式化问题
  10. 其余特色和事项
  11. 反馈

velocity template language(VTL):介绍

  VTL能够提供容易最简单最干净的方式讲动态内容放入web应用,甚至一个没有编程经验的网页开发者也能很快的使用VTL。编程

  VTL使用references将动态内容嵌入到网页里面。变量是references的一种类型能够关联到java代码中定义的变量,他也能够在网页中本身定义的参数浏览器

Hello velocity world!

  咱们开始运行第一个程序ide

1 <html>
2 <body>
3 #set( $foo = "Velocity" )
4 Hello $foo World!
5 </body>
6 <html>
View Code

  因为这个代码没有使用java传入的参数因此能够直接运行,后台模板配置好直接访问吧 修改 $foo 等于的值那么咱们就能够看到不同的结果学习

注释

  单行注释 #lua

  多行注释 #* 内容*#spa

  固然也可使用#**内容*#

 1 <html>
 2 <body>
 3 看到我1</br>##看不到我1
 4 看到我2</br>#*看不到我1 *# 
 5 看到我3
 6 #**
 7 你看不到我3
 8 *#
 9 </body>
10 <html>
View Code

  看下效果吧 这个比较简单

References

  在vtl中有三种类型的references:变量、属性和方法

  变量(Variables )

  可使用字符a-z A-Z 数字0-9 中划线 下划线组成以下

  $foo   $mudSlinger   $mud-slinger   $mud_slinger   $mudSlinger1  
  变量的值能够是使用$set指令也能够从java代码获取 如 #set( $foo = "bar" ) 那么foo的值就被设置为 bar

  属性(Properties )

  属性的使用格式是$后面加变量 加 .  好比 $foo.bar 

  方法(Method)

  好比$foo.getBar()   $foo.setBar("哈哈");

  简单点讲velocity的后两种类型其实就是能够对应到java 的一个类, 此处有补充

  咱们使用变量的时候能够增长一个大括号{} 为了防止咱们的变量和web中的字母混合在一块儿 好比 ${foo}good 就会把foo翻译 若是不加  velocity就会把整个翻译 那就会有问题了(注意 在使用指令的时候不能加{}符号 不然是会报错的)

  咱们在使用的时候最好还能够加上! 如 $!{foo} 或者 $!foo , 在使用的时候咱们知道若是没有定义的东西velocity会直接显示或者有些为null 加上!用来强制把不存在的变量显示为空白

  下面两个代码各位能够看看效果

<html>
<body>
Hello $!foo World!
</body>
<html>
View Code
<html>
<body>
Hello $foo World!
</body>
<html>
View Code

  严格模式

  velocity从1.6开始推出了严格模式, 从字面理解就是要求更严啦~好比上面出现的 未定义而使用的话就会直接泡出异常(配置属性runtime.references.strict 设置为true为严格模式)

$foo                         ## Exception
#set($bar = $foo)            ## Exception
#if($foo == $bar)#end        ## Exception
#foreach($item in $foo)#end  ## Exception
View Code

替代案例

  如今你已经熟悉了三种使用方式那么你就能够快速的进行开发。同时velocity利用了java标准从而能够更快的进行开发

$foo

$foo.getBar()
## 也能够是这样
$foo.Bar

$data.setUser("jon")
## 也能够是这样
#set( $data.User = "jon" )

$data.getRequest().getServerName()
## 也能够是这样
$data.Request.ServerName
## 也能够是这样
${data.Request.ServerName}
View Code

  其实至关于velocity本身后台进行了一次转化相似的javabean模式 实际上我以为通常般看我的咯

指令

  指令前面都是加上#符号

  #set

#set( $primate = "monkey" )
#set( $customer.Behavior = $primate )
View Code

  左边能够是变量或者对象属性 而右边只能是 变量,String,对象属性,对象方法,数字,ArrayList,Map

  下面是例子

#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( $monkey.Map = {"banana" : "good", "roast beef" : "bad"}) ## Map
View Code
#set( $foo = "bar" )
$foo
#set( $blargh = '$foo' )
$blargh


#**
bar
$foo
**#
View Code

  #if/#elseif/#else 

<html>
<body>
#if( $foo )
   <strong>Velocity!</strong>
#end
</body>
<html>
View Code

  这里执行的要求是1.foo是为true的boolean 2.foo是一个不为null,空的string或者集合 3.foo是一个不为null的对象

  看一下三种类型的简单使用

#if( $foo < 10 )
    <strong>Go North</strong>
#elseif( $foo == 10 )
    <strong>Go East</strong>
#elseif( $bar == 6 )
    <strong>Go South</strong>
#else
    <strong>Go West</strong>
#end
View Code

  #foreach

  例子 

<ul>
#foreach( $product in $allProducts )
    <li>$product</li>
#end
</ul>
View Code

allProducts 能够是vector,hashtable,array

若是是hashtable那么咱们还能够获取键值

<ul>
#foreach( $key in $allProducts.keySet() )
    <li>Key: $key -> Value: $allProducts.get($key)</li>
#end
</ul>
View Code

veloctiy还提供了简单的方法来获取循环的个数

<table>
#foreach( $customer in $customerList )
    <tr><td>$foreach.count</td><td>$customer.Name</td></tr>
#end
</table>
View Code

同时,velocity还有 $foreach.hasNext,$foreach.last,$foreach.first, 同时 你还能够在循环的时候使用#break中断

## list first 5 customers only
#foreach( $customer in $customerList )
    #if( $foreach.count > 5 )
        #break
    #end
    $customer.Name
#end
View Code

 #include

  经过该指令能够导入本身的文件(只能是静态文件,就算导入了 .vm文件也是没用的) 多个文件能够用逗号隔开

#include("cn/dota/me.txt")
View Code

#parse

  能够导入动态模板,可是只能传递一个参数用法和include同样

#evaluate

  能够动态执行一个语句 相似于js中的eval

#define

  能够定义一个相似宏的指令

#define( $block )Hello $who#end
#set( $who = 'World!' )
$block
View Code
相关文章
相关标签/搜索