类似于PHP中的Smarty,Velocity是一个基于Java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。从而实现界面和Java代码的分离,使得界面设计人员可以和java程序开发人员同步开发一个遵循MVC架构的web站点。

另外,Velocity的能力远不止web站点开发这个领域,例如,它可以从模板(template)产生SQL和PostScript、XML,它也可以被当作一个独立工具来产生源代码和报告,或者作为其他系统的集成组件使用。Velocity也可以为Turbine web开发架构提供模板服务(template service)。Velocity+Turbine提供一个模板服务的方式允许一个web应用以一个真正的MVC模型进行开发。

编写Velocity版的Hello World
获取Velocity相关JAR文件:

http://velocity.apache.org/网站上下载最新的Velocity,这里我们下载了velocity-1.7.zip

相关Jar包添加到项目中:

解压velocity-1.7.zip,发下其根目录下有两个JAR文件:

velocity-1.7.jar velocity-1.7-dep.jar

其中velocity-1.7-dep.jar包含了:

velocity-1.7.jar commons-collections-3.2.1.jar commons-lang-2.4.jar oro-2.0.8.jar(这些JAR文件位于解压目录的lib目录下)

在JAR包不冲突的情况下可以直接使用velocity-1.7-dep.jar

载类路径下添加velocity.properties文件:

该文件一般包含如下配置:

runtime.log = F:\project\MusicalInstrumentsStore\velocity_example.log
file.resource.loader.path = F:\project\MusicalInstrumentsStore\vm
input.encoding = UTF-8
output.encoding = UTF-8

untime.log指定日志文件存放位置

file.resource.loader.path指定模板的加载位置
input.encoding指定输入编码
output.encoding指定输出编码

模版的使用一共以下步骤:

1.初始化模版引擎

2.构建velocity上下文

3.变量值添加到上下文中

4.选择模版

5.合并模版和数据导出到输出流

//初始化模板引擎
Velocity.init("src/velocity.properties");
//获取VelocityContext
VelocityContext context = new VelocityContext();
//为Context设置变量
context.put("title", "HelloWorld");
context.put("author", "arthinking");
//获取模板文件
Template template = Velocity.getTemplate("helloworld.vm");
StringWriter sw = new StringWriter();
//使用模板文件的merge函数合并模板和context提供的变量,输出到StringWriter中
template.merge(context, sw);
sw.flush();
System.out.println(sw.toString());

编写helloworld.vm模板文件(保存在file.resource.loader.path设置的目录下):

${title}
${author}

一、基本语法

1、"#"用来标识Velocity的脚本语句,包括#set、#if 、#else、#end、#foreach、#end、#include、#parse、#macro等;
如:
#if($info.imgs)
<img src="$info.imgs" border=0>
#else
<img src="noPhoto.jpg">
#end

2、"$"用来标识一个对象(或理解为变量);如:$i、$msg、$TagUtil.options(...)等。

3、"{}"用来明确标识Velocity变量;
比如在页面中,页面中有一个$someonename,此时,Velocity将把someonename作为变量名,若我们程序是想在someone这个变量的后面紧接着显示name字符,则上面的标签应该改成${someone}name。

4、"!"用来强制把不存在的变量显示为空白。
如当页面中包含$msg,如果msg对象有值,将显示msg的值,如果不存在msg对象同,则在页面中将显示$msg字符。这是我们不希望的,为了把不存在的变量或变量值为null的对象显示为空白,则只需要在变量名前加一个“!”号即可。
如:$!msg

Velocity模版的基本语法:

访问对象属性

和使用EL表达式差不多,直接使用”.”导航。
如访问object对象的id属性:${object.id }

遍历List集合

#foreach($element in $list)
#element
#end

使用判断语句

#if($condition)
true
#else
false
#end

获取迭代索引值

默认使用变量名:$velocityCount
也可以自定义此变量名,在velocity.properties中设置

directive.foreach.counter.name=index  

设置索引起始位置为0

directive.foreach.counter.initial.value=0  

遍历Map变量

#foreach($key in $map.keySet())
$key : $map.get($key)
#end

在模板中进行赋值

#set(#a=”Hello World!”)
$a #set($array1=[1..10])
#foreach($entry in $array1)
#entry
#end

使用Velocity模板引擎生成文件

//初始化模板引擎
Velocity.init("src/velocity.properties");
//获取VelocityContext
VelocityContext context = new VelocityContext();
//为Context设置变量
context.put("content", "HelloWorld");
context.put("who", "arthinking");
//获取模板文件
Template template = Velocity.getTemplate("helloworld.vm");
//创建输出文件
File output = new File("D:/Velocity/1.html");
if(!output.getParentFile().exists())
output.getParentFile().mkdir();
//创建输出流
FileOutputStream outputStream = new FileOutputStream(output);
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
template.merge(context, bufferedWriter); bufferedWriter.flush();
outputStream.close();
bufferedWriter.close();

此外再增加一些 Springmvc+Velocity

在servlet-context.xml中增加以下内容,如果有jsp的配置先注释掉

<beans:bean id="velocityConfig"
<span style="white-space:pre"> </span>class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<beans:property name="resourceLoaderPath" value="/WEB-INF/views" />
<beans:property name="configLocation" value="classpath:common/velocity.properties" />
</beans:bean> <beans:bean id="velocityViewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<beans:property name="suffix" value=".htm" />
</beans:bean>

在resources/common目录下创建velocity.properties

#encoding
input.encoding =UTF-8
output.encoding=UTF-8
contentType=text/html;charset=UTF-8 #autoreload when vm changed
file.resource.loader.cache=false
file.resource.loader.modificationCheckInterval =1
velocimacro.library.autoreload=false

新建testController

@RequestMapping(value="/test")
@Controller
public class TestController {
@RequestMapping(value="/index")
public String index(Model model) {
String name = "tester";
model.addAttribute("name", name);
return "test/index";
}
}

Velocity模板引擎入门的更多相关文章

  1. velocity模板引擎学习(4)-在standalone的java application中使用velocity及velocity-tools

    通常velocity是配合spring mvc之类的框架在web中使用,但velocity本身其实对运行环境没有过多的限制,在单独的java application中也可以独立使用,下面演示了利用ve ...

  2. velocity模板引擎学习(3)-异常处理

    按上回继续,前面写过一篇Spring MVC下的异常处理.及Spring MVC下的ajax异常处理,今天看下换成velocity模板引擎后,如何处理异常页面: 一.404错误.500错误 <e ...

  3. Velocity模板引擎语法

    Velocity 模板引擎介绍 Velocity是一个基于java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template language)来引用由java ...

  4. 【转载】Velocity模板引擎的介绍和基本的模板语言语法使用

    原文地址http://www.itzhai.com/the-introduction-of-the-velocity-template-engine-template-language-syntax- ...

  5. 使用 Velocity 模板引擎快速生成代码(zhuan)

    http://www.ibm.com/developerworks/cn/java/j-lo-velocity1/ ****************************************** ...

  6. 转 如何使用velocity模板引擎开发网站

    基于 Java 的网站开发,很多人都采用 JSP 作为前端网页制作的技术,尤其在是国内.这种技术通常有一些问题,我试想一下我们是怎样开发网站的,通常有几种方法: 1:功能确定后,由美工设计网页的UI( ...

  7. 使用Velocity 模板引擎快速生成代码

    Velocity 模板引擎介绍 在现今的软件开发过程中,软件开发人员将更多的精力投入在了重复的相似劳动中.特别是在如今特别流行的MVC架构模式中,软件各个层次的功能更加独立,同时代码的相似度也更加高. ...

  8. Velocity模板引擎介绍

    整理下Velocity使用方法,整理比较详细用例 1 Velocity基础语法 1.1 用户和开发人员参考文档 http://velocity.apache.org/engine/releases/v ...

  9. Velocity 模板引擎的应用

    springboot三层机构,还有数据映射待实体.肯定需要一套模板引擎呀.那不然还手写不成. 根据我们的实际业务需求,我添加了一套数据库反向生成实体类的模板,用的是Velocity 的引擎. 不多说直 ...

随机推荐

  1. dede列表页分页地址优化(不同url相同内容问题解决)<转自http://www.966266.com>

    <注明,完全转自http://www.966266.com/seoblog/?p=75> 存在问题 DEDE默认分类分页地址存在不同URL相同内容问题,导致内容重复,对SEO非常不利.情况 ...

  2. android设置多个类似APP其中的一个为默认

    05-09 17:01:13.547: I/ActivityManager(3003): START u0 {act=android.intent.action.VIEW cat=[android.i ...

  3. 网站建设中前端常用的jQuery+easing缓动的动画

    网站建设中前端人员利用jQuery实现动画再简单不过了,只是要实现更酷的效果还需要插件来帮忙,easing就是一款帮助jQuery实现缓动动画的插件,经过试用,效果很不错! 下载该插件:jquery. ...

  4. LeetCode OJ-- Clone Graph **@

    https://oj.leetcode.com/problems/clone-graph/ 图的拷贝,就是给一个图,再弄出一个一模一样的来. /** * Definition for undirect ...

  5. View的事件处理流程

    一直对view的事件处理流程迷迷糊糊,今天花了点时间写了个栗子把它弄明白了. 1.view的常用的事件分为:单击事件(onClick).长按事件(onLongClick).触摸事件(onTouch), ...

  6. java操作word,excel,pdf

    在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...

  7. Jade之Case

    Case jade中的case类似js中的switch语句. 当前一个when中无语句的时候,将一直往下直至遇到一个有语句的when才跳出. jade: - var friends = 10 case ...

  8. HDU 5023 A Corrupt Mayor's Performance Art (据说是线段树)

    题意:给定一个1-n的墙,然后有两种操作,一种是P l ,r, a 把l-r的墙都染成a这种颜色,另一种是 Q l, r 表示,输出 l-r 区间内的颜色. 析:应该是一个线段树+状态压缩,但是我用s ...

  9. 【转】require.js学习笔记(二)

    require.js遵循AMD规范,通过define定义模块,require异步加载模块,一个js文件即一个模块. 一.模块加载require1.加载符合AMD规范模块 HTML: <scrip ...

  10. [原] XAF 如何将数据库中Byte array图片显示出来

    问题比较简单,直接上代码. private Image _Cover; [Size(SizeAttribute.Unlimited), ValueConverter(typeof(ImageValue ...