Velocity是由Apache软件组织提供的一项开放源码项目,它是一个基于Java的模板引擎。
通过Velocity模板语言(Velocity Template Language,VTL)定义模板(Template),并且在模板中不包含任何Java程序代码。
Java开发人员编写程序代码来设置上下文(Context),它包含了用于填充模板的数据。
Velocity引擎能够把模板和上下文合并起来,生成相关内容。
Velocity是一种后台代码和前台展示分离的一种设计。

velocity由以下几部分组成:

(1)指定runtime.log对应的日志文件(可选),Velocity.init()中使用;
(2)创建模板文件。默认以.vm结尾(模板的内容也可以写在代码中),由生成org.apache.velocity.Template对象的org.apache.velocity.app.Velocity.getTemplate(templateFile)使用; 
      Tips:模板文件要放在项目根目录下,否则不能正常加载
(3)模板中需要使用的动态数据。存放在org.apache.velocity.VelocityContext对象中,VelocityContext中使用map存放数据;
(4)输出最终生成的内容,javaapp和javaweb中不同

java app中

使用org.apache.velocity.Template.merge(...,context.., writer),这个方法有多个重载方法.其中writer是实现writer接口的io对象

/*
             *  Now have the template engine process your template using the
             *  data placed into the context.  Think of it as a  'merge'
             *  of the template and the data to produce the output stream.
             */

javaweb中

访问servlet返回org.apache.velocity.Template对象,即可在浏览器中展示(可以认为是一个前端页面,内容浏览器传动解析)

其它:
使用log4j来输出velocity的日志:

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.Log4JLogChute;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator; /**
* Simple example class to show how to use an existing Log4j Logger
* as the Velocity logging target.
*/
public class Log4jLoggerExample
{
public static String LOGGER_NAME = "velexample"; public static void main( String args[] )
throws Exception
{
/*
* configure log4j to log to console
*/
BasicConfigurator.configure(); Logger log = Logger.getLogger(LOGGER_NAME); log.info("Hello from Log4jLoggerExample - ready to start velocity"); /*
* now create a new VelocityEngine instance, and
* configure it to use the logger
*/
VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
"org.apache.velocity.runtime.log.Log4JLogChute"); ve.setProperty(Log4JLogChute.RUNTIME_LOG_LOG4J_LOGGER, LOGGER_NAME); ve.init(); log.info("this should follow the initialization output from velocity");
}
}

Velocity模板使用的赋值及流程控制语法:
VTL:
注释:
单行注释的前导符为“##”;多行注释则采用“#*”和“*#”符号

引用:
在VTL中有3种类型的引用:变量、属性和方法
变量引用的简略标记是由一个前导“$”字符后跟一个VTL标识符“Identifier”组成的。一个VTL标识符必须以一个字母开始(a...z或A...Z),剩下的字符将由以下类型的字符组成:
a.字母(a...z,A...Z)
b.数字(0...9)
c.连字符("-")
d.下划线("_")
给变量赋值有两种方法,
通过java代码给Context赋值,然后由Velocity引擎将Context与Template结合;
通过#set指令给变量赋值;

正式引用符(Formal Reference Notation):示例 ${purchaseMoney}

正式引用符多用在引用变量和普通文件直接邻近的地方

当Velocity遇到一个未赋值的引用时,会直接输出这个引用的名字。如果希望在没有赋值时显示空白,则可以使用安静引用符(Quiet Reference Notation)绕过Velocity的常规行为,以达到希望的效果。安静引符的前导字符为“$!变量名”

1.变量定义

变量名的有效字符集:

$ [ ! ][ { ][ a..zA..Z ][ a..zA..Z0..9-_ ][ } ]

Examples:

  • 一般方式: $mud-Slinger_9
  • 静态(输出原始字面): $!mud-Slinger_9
  • 正规格式: ${mud-Slinger_9}

http://www.cnblogs.com/netcorner/archive/2008/07/11/2912125.html

Velocity中加载vm文件的三种方式

 
velocitypropertiespath
Velocity中加载vm文件的三种方式:
  
方式一:加载classpath目录下的vm文件
Properties p = new Properties();
p.put("file.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(p);
...
Velocity.getTemplate(templateFile);
  
  
方式二:根据绝对路径加载,vm文件置于硬盘某分区中,如:d://tree.vm
Properties p = new Properties();
p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "d://");
Velocity.init(p);
...
Velocity.getTemplate("tree.vm");
  
  
方式三:使用文本文件,如:velocity.properties,配置如下:
#encoding
input.encoding=UTF-8
output.encoding=UTF-8
contentType=text/html;charset=UTF-8
不要指定loader.
 
  
再利用如下方式进行加载
Properties p = new Properties();
p.load(this.getClass().getResourceAsStream("/velocity.properties"));
Velocity.init(p);
...
Velocity.getTemplate(templateFile);
 
package com.study.volicity;
 
import java.io.IOException;
import java.io.StringWriter;
import java.util.Properties;
 
import org.apache.velocity.app.Velocity;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
 
public class Test {
     
 
    public static void main(String args[]) throws IOException {
 
        Properties pros = new Properties();
        pros.load(Test.class.getClassLoader().getResourceAsStream("velocity.properties"));
        Velocity.init(pros);
        VelocityContext context = new VelocityContext();
 
        context.put("name""Velocity");
        context.put("project""Jakarta");
 
        /* lets render a template 相对项目路径 */
        Template template = Velocity.getTemplate("/view/header.vm");
 
        StringWriter writer = new StringWriter();
 
        /* lets make our own string to render */
        template.merge(context, writer);
        System.out.println(writer);
    }
 
}
 
http://www.cnblogs.com/c-abc/p/4829084.html
 
package velocity;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine; import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties; /**
* Created by 10159705 on 16-3-28.
*/
public class VelocityDemo { public static void main(String[] args) throws IOException { VelocityContext context = new VelocityContext();
context.put("name", "VName");
context.put("project", "JakProject"); String path = VelocityDemo.class.getResource("/velocity/").getPath();//example2.vm
System.out.println(path);
Properties p = new Properties();
p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);
Velocity.init(p); Template template = Velocity.getTemplate("example2.xml", "GBK");
Writer writer = new BufferedWriter(new FileWriter("result.xml"));
template.merge(context, writer);
writer.flush();
writer.close(); }
}

example2.xml

<?xml version="1.0" encoding="GB2312"?>
<root>
Hello from ${name} in the $!project project.
</root>

velocity-1.7学习笔记的更多相关文章

  1. [原创]java WEB学习笔记58:Struts2学习之路---Result 详解 type属性,通配符映射

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  2. box2dweb 学习笔记--sample讲解

    前言: 之前博文"台球游戏的核心算法和AI(1)" 中, 提到过想用HTML5+Box2d来编写实现一个台球游戏. 以此来对比感慨一下游戏物理引擎的巨大威力. 做为H5+box2d ...

  3. webx学习笔记

    Webx学习笔记周建旭 2014-08-01 Webx工作流程 图 3.2. Webx Framework如何响应请求 当Webx Framework接收到一个来自WEB的请求以后,实际上它主要做了两 ...

  4. jfinal框架教程-学习笔记

    jfinal框架教程-学习笔记 JFinal  是基于 Java  语言的极速  WEB  + ORM  开发框架,其核心设计目标是开发迅速.代码量少.学习简单.功能强大.轻量级.易扩展.Restfu ...

  5. Webx3学习笔记(2)——基本流程

    Webx3项目是运行在jetty/tomcat这种Web应用容器中的,Web应用的模式都是请求-响应的.一个请求通过浏览器发出,封装为HTTP报文到达服务端,被容器接受到,封装为HttpRequest ...

  6. V-rep学习笔记:关节力矩控制

    Torque or force mode When the joint motor is enabled and the control loop is disabled, then the join ...

  7. V-rep学习笔记:Reflexxes Motion Library 3

    路径规划 VS 轨迹规划 轨迹规划的目的是将输入的简单任务描述变为详细的运动轨迹描述.注意轨迹和路径的区别:Trajectory refers to a time history of positio ...

  8. V-rep学习笔记:Reflexxes Motion Library 2

    VREP中的simRMLMoveToPosition函数可以将静态物体按照设定的运动规律移动到指定的目标位置/姿态.If your object is dynamically enabled, it ...

  9. VueJs 学习笔记

    VueJs学习笔记 参考资料:https://cn.vuejs.org/ 特效库:TweenJS(补间动画库)  VelocityJS(轻量级JS动画库) Animate.css(CSS预设动画库) ...

  10. Spring实战第六章学习笔记————渲染Web视图

    Spring实战第六章学习笔记----渲染Web视图 理解视图解析 在之前所编写的控制器方法都没有直接产生浏览器所需的HTML.这些方法只是将一些数据传入到模型中然后再将模型传递给一个用来渲染的视图. ...

随机推荐

  1. Java内存溢出的详细解决方案

    本文介绍了Java内存溢出的详细解决方案.本文总结内存溢出主要有两种情况,而JVM经常调用垃圾回收器解决内存堆不足的问题,但是有时仍会有内存不足的错误.作者分析了JVM内存区域组成及JVM设置虚拟内存 ...

  2. Ext.Net学习笔记15:Ext.Net GridPanel 汇总(Summary)用法

    Ext.Net学习笔记15:Ext.Net GridPanel 汇总(Summary)用法 Summary的用法和Group一样简单,分为两步: 启用Summary功能 在Feature标签内,添加如 ...

  3. QT5新手上路(2)发布exe文件

    QT编程教程在网上有很多,但写完代码以后如何打包成可执行exe文件却少有提及,本文主要介绍这一部分:1.首先确认自己建的工程在debug模式下运行无误.2.在release模式下运行一遍.(如何更改成 ...

  4. away3d打包到IOS锯齿问题解决办法

    很多ios设备是高清屏,一个像素顶普通设备四个像素.从这点上也许可以入手解决. 先把<requestedDisplayResolution>high</requestedDispla ...

  5. 排序算法ONE:选择排序SelectSort

    /** *选择排序: * 对冒泡排序的一个改进 * 进行一趟排序时,不用每一次都交换,只需要把最大的标示记下 * 然后再进行一次交换 */ public class SelectSort { /** ...

  6. iOS数据库操作流程

    SQLite最新的版本是3.0,使用之前应该先导入libsqlite3.0.dylib 1.导入流程 2.iOS中操作数据库的流程 打开数据库 准备SQL数据库 执行SQL数据库 语句完结 关闭数据库 ...

  7. Android AndroidManifest学习笔记

    <application>标签 : android:allowBackup="true" 数据可以备份 <activity>标签:configChanges ...

  8. php中的preg系列函数

    mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int ...

  9. redis 安装注意事项

    redis安装 1.redis 安装 官网地址:http://redis.io/download $ wget http://download.redis.io/releases/redis-3.0. ...

  10. 折腾了一早上的C# WPF ListView+Grid 实现图片+文字 自动换行排列 类似Windows资源管理器效果

    <ListBox Name="lstFileManager" Background ="Transparent" ItemsSource="{B ...