美文网首页VelocityJava
Velocity 快速入门教程

Velocity 快速入门教程

作者: FX_SKY | 来源:发表于2017-03-09 19:27 被阅读1108次

Apache Velocity 是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。
官网介绍如下:

Velocity is a template engine that can be used for many purposes. Some common types of applications which use Velocity are:

  • Web applications. Web designers create HTML pages with placeholders for dynamic information. The page is processed with VelocityViewServlet or any of a number of frameworks which support Velocity. This approach to web application development is called Model-View-Controller or MVC and is intended to be a direct replacement for applications developed with Java Server Pages (JSPs) or PHP.
  • Source code generation. Velocity can be used to generate Java source code, SQL, or PostScript based on templates. The PoweredByVelocity page lists a number of open source and commercial development software packages which use Velocity in this manner.
  • Automatic emails. Many applications generate automatic emails for account signup, password reminders or automatically sent reports. Using Velocity, the email template can be stored in a text file rather than directly embedded in your Java code.
  • XML transformation. Velocity provides an ant task called Anakia which reads an XML file and makes it available to a Velocity template. A common application is to convert documentation stored in a generic "xdoc" format into a styled HTML document.
    Since version 2.0, Velocity can also be integrated as a scripting engine into the Java Scripting Language Framework (as defined by the JSR-223 specification).

Velocity 主要使用场景如下:

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

VTL语法使用

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

一、变量

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

  1. 变量定义
#set($name =“velocity”)

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

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

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

  1. 变量的使用
    在模板文件中使用$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;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @date 2017-03-10 13:44
 */
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());
    }
}

2、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;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @date 2017-03-10 13:48
 */
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();

参考资料

Developer Guide

相关文章

网友评论

    本文标题:Velocity 快速入门教程

    本文链接:https://www.haomeiwen.com/subject/txdggttx.html