Velocity快速入门

Velocity 介绍

Velocity是一个基于java的模板引擎。它允许任何人使用简单但功能强大的模板语言引用Java代码中定义的对象。

当Velocity用于web开发时,web设计人员可以与Java程序员并行工作,根据模型-视图-控制器(MVC)模型开发web站点,这意味着web页面设计人员可以只专注于创建看起来不错的站点,而程序员可以只专注于编写一流的代码。Velocity将Java代码从web页面中分离出来,使web站点在其生命周期内更具可维护性,并为Java服务器页面(jsp)或PHP提供了一个可行的替代方案。

Velocity的功能远远超出了web的范围;例如,它可以用来从模板生成SQL、PostScript和XML。它既可以作为生成源代码和报告的独立实用程序使用,也可以作为其他系统的集成组件使用。例如,Velocity为各种web框架提供模板服务,使它们能够使用视图引擎,以便根据真正的MVC模型开发web应用程序。

Velocity 主要使用场景

  1. Web 应用:开发者在不使用 JSP 的情况下,可以用 Velocity 让 HTML 具有动态内容的特性。
  2. 源代码生成:Velocity 可以被用来生成 Java 代码、SQL 或者 PostScript。
  3. 自动 Email:很多软件的用户注册、密码提醒或者报表都是使用 Velocity 来自动生成的。
  4. 转换 xml。

VTL语法使用

在 Velocity 中所有的关键字都是以#开头的,而所有的变量则是以$开头。Velocity 的语法类似于 JSP 中的 JSTL,甚至可以定义类似于函数的宏,下面来看看具体的语法规则。

一、变量

和我们所熟知的其他编程语言一样,Velocity 也可以在模板文件中有变量的概念。

变量定义

#set($name =“velocity”)

等号后面的字符串 Velocity 引擎将重新解析,例如出现以$开始的字符串时,将做变量的替换。

#set($hello =“hello $name”)

上面的这个等式将会给 $hello 赋值为“hello velocity”

变量的使用

在模板文件中使用$name 或者 ${name} 来使用定义的变量。推荐使用 ${name} 这种格式,因为在模板中同时可能定义了类似$name 和 $names 的两个变量,如果不选用大括号的话,引擎就没有办法正确识别 $names 这个变量。

#set($name =“ricky”)
Welcome $name to velocity\.com

二、循环

在 Velocity 中循环语句的语法结构如下:

#foreach($element in $list)
 This is $element
 $velocityCount
#end

Velocity 引擎会将 list 中的值循环赋给 element 变量,同时会创建一个 $velocityCount 的变量作为计数,从 1 开始,每次循环都会加 1

三、条件语句

条件语句的语法如下:

#if(condition)
#elseif(condition)
#else
#end

四、关系操作符

Velocity 引擎提供了 AND、OR 和 NOT 操作符,分别对应&&、||和! 例如:

#if($foo && $bar)
#end

五、宏

Velocity 中的宏可以理解为函数定义。定义的语法如下:

#macro(macroName arg1 arg2 …)
#end

调用这个宏的语法是:

#macroName(arg1 arg2 …)

这里的参数之间使用空格隔开,下面是定义和使用 Velocity 宏的例子:

#macro(sayHello $name)
hello $name
#end

#sayHello(“velocity”)

输出的结果为 hello velocity

六、#parse 和 #include

#parse 和 #include 指令的功能都是在外部引用文件,而两者的区别是:#parse 会将引用的内容当成类似于源码文件,会将内容在引入的地方进行解析,#include 是将引入文件当成资源文件,会将引入内容原封不动地以文本输出。分别看以下例子:

foo.vm 文件:
#set($name =“velocity”)

parse.vm:
#parse(“foo.vm”)

输出结果为:velocity

include.vm:
#include(“foo.vm”)

输出结果为:#set($name =“velocity”)

API实战

  1. Singleton Model
    使用 org.apache.velocity.app.Velocity类
package com.bytebeats.velocity.sample;

import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;

public class SingletonModelDemo {

    public static void main(String[] args) {

        Velocity.init();

        VelocityContext context = new VelocityContext();
        context.put("name", "Velocity");

        Template template = null;
        try {
            template = Velocity.getTemplate("mytemplate.vm");
        } catch( ResourceNotFoundException e ) {
            // couldn't find the template
        } catch( ParseErrorException pee ) {
            // syntax error: problem parsing the template
        } catch( MethodInvocationException mie ) {
            // something invoked in the template
            // threw an exception
        } catch( Exception e ) {

        }

        StringWriter sw = new StringWriter();
        template.merge(context, sw);

        System.out.println("content:"+sw.toString());
    }
}
  1. Separate Instance
    使用org.apache.velocity.app.VelocityEngine,如下:
package com.bytebeats.velocity.sample;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import java.io.StringWriter;

public class SeparateInstanceDemo {

    public static void main(String[] args) {

        //1. create a new instance of the engine
        VelocityEngine ve = new VelocityEngine();

        //2. configure the engine
        ve.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath");

        //3. initialize the engine
        ve.init();

        VelocityContext context = new VelocityContext();
        context.put("name", "Velocity");
        
        Template template = ve.getTemplate("foo.vm");
        StringWriter sw = new StringWriter();
        template.merge(context, sw);

        System.out.println("content:"+sw.toString());
    }
}

还有另外一种方式来配置:

Properties props = new Properties();
props.load(this.getClass().getResourceAsStream("/vm.properties"));
VelocityEngine ve = new VelocityEngine(props);
ve.init();

官方文档:http://velocity.apache.org/

猜你喜欢

转载自www.cnblogs.com/tqlin/p/10643372.html