Velocity入门系列

Velocity介绍

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

简单的环境搭建

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

  

 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 !!!!!!!!

目录

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

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

velocity template language(VTL):介绍

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

  VTL使用references将动态内容嵌入到网页里面。变量是references的一种类型可以关联到java代码中定义的变量,他也可以在网页中自己定义的参数

Hello velocity world!

  我们开始运行第一个程序

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

  由于这个代码没有使用java传入的参数所以可以直接运行,后台模板配置好直接访问吧 修改 $foo 等于的值那么我们就可以看到不一样的结果

注释

  单行注释 #

  多行注释 #* 内容*#

  当然也可以使用#**内容*#

 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

 

转载于:https://www.cnblogs.com/jsepc01-/p/5472266.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值