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. Jsp与servlet之间页面跳转及参数传递实例(转)

    原网址:http://blog.csdn.net/ssy_shandong/article/details/9328985 11. jsp与servlet之间页面跳转及参数传递实例 分类: Java ...

  2. 客官,您的 Flask 全家桶请收好

    http://www.factj.com/archives/543.html Flask-AppBuilder          - Simple and rapid Application buil ...

  3. sea.js总结

    SeaJS是一个遵循CommonJS规范的JavaScript模块加载框架. 参考以下网址进行详细学习: https://segmentfault.com/a/1190000000357191?pag ...

  4. JavaScript中关于创建对象的笔记

    1,最基本的两种创建对象的方式:构造函数|| 字面量 构造函数: var person = new Object(); person.name = "chen1zee1"; per ...

  5. 快速开启Windows 的各种任务及 bat(ch)脚本

    MSC It is the Microsoft Management Console Snap-in Control File, like services.msc, devmgmt.msc (Dev ...

  6. linux下查看端口的连接数

    linux下,可以通过natstat命令来查看端口的连接状况,比如连接数 例如,查看9090端口的连接状况: 查看某个端口的连接数netstat -nat | grep -iw "9090& ...

  7. asp.net mvc上传头像加剪裁功能介绍

    正好项目用到上传+剪裁功能,发上来便于以后使用. 我不能告诉你们其实是从博客园扒的前台代码,哈哈. 前端是jquery+fineuploader+jquery.Jcrop 后台是asp.net mvc ...

  8. C#动态生成图书信息XML文件

    通过C#动态生成图书信息XML文件,下面有个不错的示例,需要的朋友可以参考下 通过C#动态生成图书信息XML文件(Books.xml),文件如下: 复制代码代码如下: <?xml version ...

  9. Angular 动态生成html中 ng-click无效

    bodyApp.controller('customersCtrl', function ($scope, $http, cfpLoadingBar,$compile) { $scope.test = ...

  10. PHP 向 MySql 中数据修改操作时,只对数字操作有效,非数字操作无效,怎么办?

    问题描述:   用PHP向MySql数据库中修改数据,实现增删改(数据库能正确连接) 经测试,代码只能对数字进行正常的增删改操作,非数字操作无效   但要在课程名称中输入中文,应该如果修改呢?   存 ...