一、载入Velocity依赖包

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

二、Velocity类

package com.qunar.piao.data.integration.common;

import java.io.ByteArrayInputStream;
import java.io.CharArrayWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map; import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context; /**
* Velocity引擎帮助类
*
*/
public class VelocityHelper {
/** 单态实例 */
private static final VelocityHelper instance = new VelocityHelper(); /** 私有构造函数 */
private VelocityHelper() {
// 初始化velocity的信息 主要设置一些Velocity的默认属性 // 初始化
try {
Velocity.init();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* <pre>
* 取得实例
* </pre>
*/
public static VelocityHelper getInstance() {
return instance;
} /**
* <pre>
* 渲染:从reader到writer
* </pre>
*
* @param context
* @param writer
* @param reader
* @return
*/
public boolean evaluate(Context context, Writer writer, Reader reader) {
try {
return Velocity.evaluate(context, writer, "", reader);
} catch (Exception e) {
throw new RuntimeException("velocity evaluate error! detail [" + e.getMessage() + "]");
}
} /**
* <pre>
* 通过Map过滤一个输入流
* </pre>
*
* @param map
* @param reader
* @return
*/
@SuppressWarnings("unchecked")
public InputStream evaluate(Map map, Reader reader) {
try {
// 把产生的输出流(字符流),转换成输入流(字节流)
byte[] dataBytes = this.evaluateToWriter(map, reader).toString().getBytes();
return new ByteArrayInputStream(dataBytes);
} catch (Exception e) {
throw new RuntimeException("velocity evaluate error! detial [" + e.getMessage() + "]");
}
} /**
* <pre>
* 通过Map过滤一个输入流
* </pre>
*
* @param map
* @param reader
* @return
*/
@SuppressWarnings("unchecked")
public Writer evaluateToWriter(Map map, Reader reader) {
try {
VelocityContext context = convertVelocityContext(map);
CharArrayWriter writer = new CharArrayWriter();
// 开始评估
this.evaluate(context, writer, reader); return writer;
} catch (Exception e) {
throw new RuntimeException("velocity evaluate error! detail [" + e.getMessage() + "]");
}
} /**
* <pre>
* 取得Velocity系统属性
* </pre>
*
* @param key
* @return
*/
public Object getProperty(String key) {
return Velocity.getProperty(key);
} /**
* <pre>
* 把Map转换成Context
* </pre>
*/
private VelocityContext convertVelocityContext(Map<String, Object> map) {
VelocityContext context = new VelocityContext();
if (map == null) {
return context;
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
return context;
} /**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", "2011-11-21");
map.put("weather", "晴朗 李秋"); Reader reader = new FileReader("D:\\index.vm");
Writer writer = VelocityHelper.getInstance().evaluateToWriter(map, reader); // 今天是:2011-11-21,天气:晴朗 李秋!
System.out.println(writer.toString());
}
}

三、在D盘添加模版文件

今天是:${date},天气:${weather}!

四、运行VelocityHelper

今天是:2011-11-21,天气:晴朗 李秋!

五、Velocity语法总结

5.1 设置变量

#set( $test = $test2 + 3)

#set( $test.a = "abc")

#set( $test.b = 1)

5.2 循环

#foreach($conversionRate in $conversionRateList)
$velocityCount //第几个,从1开始
#foreach($member in $conversionRate.entrySet())
$velocityCount //第几个,从1开始
$member.value //值
#end
#end

5.3 if判断

#if ($foo < 10)
Go North
#elseif ($foo== 10)
Go East
#else
Go West
#end

5.4 字符串截取

$member.value.substring(0,1)

5.5 字符串长度

$!{str.length()}

参考:

http://velocity.apache.org/tools/releases/1.3/generic/

http://www.360doc.com/content/11/1203/22/834950_169480722.shtml

Velocity使用总结的更多相关文章

  1. Velocity笔记--使用Velocity获取动态Web项目名的问题

    以前使用jsp开发的时候,可以通过request很轻松的获取到根项目名,现在换到使用velocity渲染视图,因为已经不依赖servlet,request等一些类的环境,而Web项目的根项目名又不是写 ...

  2. Velocity初探小结--velocity使用语法详解

    做java开发的朋友一般对JSP是比较熟悉的,大部分人第一次学习开发View层都是使用JSP来进行页面渲染的,我们都知道JSP是可以嵌入java代码的,在远古时代,java程序员甚至在一个jsp页面上 ...

  3. Velocity初探小结--Velocity在spring中的配置和使用

    最近正在做的项目前端使用了Velocity进行View层的数据渲染,之前没有接触过,草草过了一遍,就上手开始写,现在又回头细致的看了一遍,做个笔记. velocity是一种基于java的模板引擎技术, ...

  4. 记录一次bug解决过程:velocity中获取url中的参数

    一.总结 在Webx的Velocity中获取url中参数:$rundata.getRequest().getParameter('userId') 在Webx项目中,防止CSRF攻击(Cross-si ...

  5. velocity中$springMacroRequestContext.getMessage($code)

    在Java国际化(i18n)中, vm页面显示内容需要使用 #springMessage("title") 实际运行时发现页面输出$springMacroRequestContex ...

  6. Velocity 局部定制模板

    Velocity介绍 Velocity是一个基于java的template engine.它允许Web designer引用Java Code中定义的方法.Web designer可以和Java工程师 ...

  7. 只需2分钟,简单构建velocity web项目

    Velocity是一个基于java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象 velocity ...

  8. Velocity简单语法及VelocityHelper封装

    1.简单替换##这是注释Wellcome ${userName}! Now:$date 2.申明变量:#set( $iAmVariable = "good!" )Welcome $ ...

  9. Velocity 语法(转)

    一.基本语法 1."#"用来标识Velocity的脚本语句,包括#set.#if .#else.#end.#foreach.#end.#iinclude.#parse.#macro ...

  10. springmvc配置多视图 - tiles, velocity, freeMarker, jsp

    转自: http://www.cnblogs.com/shanheyongmu/p/5684595.html <!-- Velocity --> <bean id="vel ...

随机推荐

  1. 【CentOS】centos7 稳定使用版本,centos镜像的下载

    命令: cat /etc/redhat-release 下载地址: https://wiki.centos.org/Download 下载版本:

  2. ASP.NET MVC:mvc pattern

    There are three pieces to the MVC pattern: The model—The domain that your software is built around. ...

  3. webrtc fec

    转自:http://www.cnblogs.com/webrtc/p/7402570.html WebRTC::FEC [TOC] Tags: WebRTC FEC WebRTC中的 FEC 实现分为 ...

  4. IP视频通信中的"丢包恢复技术”(LPR)

    转自:http://blog.csdn.net/blade2001/article/details/9094709 在IP视频通话中,即使是在丢包率很小的情况下也会对使用效果造成较为明显的影响.正是由 ...

  5. Material Designer的低版本兼容实现(八)—— Flat Button

       除了中规中矩的矩形按钮外,5.0中将按钮扁平化,产生了一个扁平按钮——Flat Button.这个按钮降低了很多存在感,主要用于在对话框,提示栏中.让整个界面减少层级.今天说的就是它的用法. 这 ...

  6. SVG Path路径使用(一)

    一.<path> 标签 <path> 标签用来定义路径. 下面的命令可用于路径数据: M = moveto L = lineto H = horizontal lineto V ...

  7. Asp.Net WebApi开启Session回话

    一.在WebApi项目中默认没有开启Session回话支持.需要在Global中的Init()方法中指定会员需要支持的类型 public class WebApiApplication : Syste ...

  8. Google和Baidu的站内搜索代码

    <!-- SiteSearch Google --> <form method="get" action="http://www.google.com/ ...

  9. 第三十二章 elk(3)- broker架构 + 引入logback

    实际中最好用的日志框架是logback,我们现在会直接使用logback通过tcp协议向logstash-shipper输入日志数据.在上一节的基础上修改!!! 一.代码 1.pom.xml < ...

  10. scrapy框架系列 (3) Item Pipline

    item pipeline 当Item在Spider中被收集之后,它将会被传递到Item Pipeline,这些Item Pipeline组件按定义的顺序处理Item. 每个Item Pipeline ...