velocity-1.7学习笔记
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..z, A..Z ][ a..z, A..Z, 0..9, -, _ ][ } ]
Examples:
- 一般方式: $mud-Slinger_9
- 静态(输出原始字面): $!mud-Slinger_9
- 正规格式: ${mud-Slinger_9}
http://www.cnblogs.com/netcorner/archive/2008/07/11/2912125.html
Velocity中加载vm文件的三种方式
velocitypropertiespathVelocity中加载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.vmProperties p = new Properties();p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "d://");Velocity.init(p);...Velocity.getTemplate("tree.vm"); 方式三:使用文本文件,如:velocity.properties,配置如下:#encodinginput.encoding=UTF-8output.encoding=UTF-8contentType=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); }}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学习笔记的更多相关文章
- [原创]java WEB学习笔记58:Struts2学习之路---Result 详解 type属性,通配符映射
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- box2dweb 学习笔记--sample讲解
前言: 之前博文"台球游戏的核心算法和AI(1)" 中, 提到过想用HTML5+Box2d来编写实现一个台球游戏. 以此来对比感慨一下游戏物理引擎的巨大威力. 做为H5+box2d ...
- webx学习笔记
Webx学习笔记周建旭 2014-08-01 Webx工作流程 图 3.2. Webx Framework如何响应请求 当Webx Framework接收到一个来自WEB的请求以后,实际上它主要做了两 ...
- jfinal框架教程-学习笔记
jfinal框架教程-学习笔记 JFinal 是基于 Java 语言的极速 WEB + ORM 开发框架,其核心设计目标是开发迅速.代码量少.学习简单.功能强大.轻量级.易扩展.Restfu ...
- Webx3学习笔记(2)——基本流程
Webx3项目是运行在jetty/tomcat这种Web应用容器中的,Web应用的模式都是请求-响应的.一个请求通过浏览器发出,封装为HTTP报文到达服务端,被容器接受到,封装为HttpRequest ...
- V-rep学习笔记:关节力矩控制
Torque or force mode When the joint motor is enabled and the control loop is disabled, then the join ...
- V-rep学习笔记:Reflexxes Motion Library 3
路径规划 VS 轨迹规划 轨迹规划的目的是将输入的简单任务描述变为详细的运动轨迹描述.注意轨迹和路径的区别:Trajectory refers to a time history of positio ...
- V-rep学习笔记:Reflexxes Motion Library 2
VREP中的simRMLMoveToPosition函数可以将静态物体按照设定的运动规律移动到指定的目标位置/姿态.If your object is dynamically enabled, it ...
- VueJs 学习笔记
VueJs学习笔记 参考资料:https://cn.vuejs.org/ 特效库:TweenJS(补间动画库) VelocityJS(轻量级JS动画库) Animate.css(CSS预设动画库) ...
- Spring实战第六章学习笔记————渲染Web视图
Spring实战第六章学习笔记----渲染Web视图 理解视图解析 在之前所编写的控制器方法都没有直接产生浏览器所需的HTML.这些方法只是将一些数据传入到模型中然后再将模型传递给一个用来渲染的视图. ...
随机推荐
- Sqlserver 快照
最近,开发系统使用SqlServer2008 R2,但是由于系统数据压力的增加,准备增加一个和正式数据库同步的库,用来供接口和报表使用,所以开始对SqlServer里面的一些技术开始研究,第一篇先来研 ...
- extjs类的生命周期
只要extjs对应的类文件加载了,那么该类就可以构造对象或者用来继承了.
- (一)问候Spring4
第一节:Spring 简介 Spring 作者:Rod Johnson: 官方网站:http://spring.io/ 最新开发包及文档下载地址:http://repo.springsource.or ...
- 第十二篇、高度自适应的textView
高度根据输入内容变化输入框,我们在很多的应用上都可以见到,如微信.QQ聊天,QQ空间评论等等,该输入框可以用xib,纯代码编写,但是个人觉得纯代码编写用起来更加方便一些. 1.使用自定义的UIView ...
- SpringInAction读书笔记--第2章装配Bean
实现一个业务需要多个组件相互协作,创建组件之间关联关系的传统方法通常会导致结构复杂的代码,这些代码很难被复用和单元测试.在Spring中,对象不需要自己寻找或创建与其所关联的其它对象,Spring容器 ...
- 暑假集训(2)第四弹 ----- 敌兵布阵(hdu1166)
D - 敌兵布阵 Crawling in process... Crawling failed Time Limit:1000MS Memory Limit:32768KB 64bit ...
- 九度OJ 1283 第一个只出现一次的字符
题目地址:http://ac.jobdu.com/problem.php?pid=1283 题目描述: 在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现 ...
- [可拖动DIV]刚开通博客顺便就写了点东西!
说说我自己的思路 首先需要一个初始div div { border: 1px #333 solid; width: 200px; height: 50px; } <div id="od ...
- 动态链接库找不到 : error while loading shared libraries: libgsl.so.0: cannot open shared object file: No such file or directory
问题: 运行gsl(GNU scientific Library)的函数库,用 gcc erf.c -I/usr/local/include -L/usr/local/lib64 -L/usr/loc ...
- linux 源码安装软件原理
make 与 configure 在使用类似 gcc 的编译器来进行编译的过程并不简单,因为一套软件并不会仅有一支程序,而是有一堆程序码文件.所以除了每个主程序与副程序均需要写上一笔编译过程的命令外, ...