一、载入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. C# 其他图片格式转emf

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  2. python测试开发django-40.模型(model)中choices使用

    前言 之前一直在想页面上如果一个字段只有固定的几个选项,类似select下拉框这种,如果在表里面设置一个外键的话,是不是有点傻了,这样为了几个选项弄一张表不值得. 后来看到Django模型中的字段有个 ...

  3. Linux内核list/hlist解读

    转自:http://blog.chinaunix.net/uid-20671208-id-3763131.html 目录 1. 前言 2 2. 通用宏 2 2.1. typeof 2 2.1.1. 定 ...

  4. HikariCP 脑火Failed to obtain JDBC Connection: You need to run the CLI build and you need target/classes in your classpath to run.

    测试了一下 HikariCP 连接池报错,无解 十一月 16, 2017 5:31:59 下午 org.apache.catalina.core.StandardContext loadOnStart ...

  5. 苹果无法连接到itunes store怎么办

    方法1:设置--还原--还原网络设置,再进app store就可以了.方法2:重置访问限制“设置”–> “通用” –> “访问限制”,开启访问限制5秒,然后再关闭访问限制.方法3:重置当前 ...

  6. Android实现图片裁剪

    MainActivity.java package com.kale.imagetailor; import java.io.File; import java.io.FileNotFoundExce ...

  7. Leetcode刷题记录:构建最大数二叉树

    题目要求,题目地址 给定一个不含重复数字的数组,最大二叉树构建规则如下: 1.根是数组中最大的数字 2.左边的子树是最大数字左边的内容 3.右边的子树是最大数字右边的内容 答案 class Solut ...

  8. C# Process获取当前进程信息

    1.获取当前进程信息整理 Process.GetCurrentProcess(),返回当前程序的进程对象. Process cur = Process.GetCurrentProcess(); //当 ...

  9. ImportError: No module named caffe.proto解决办法

    原文   https://blog.csdn.net/lanyuelvyun/article/details/73628152 在用自己的数据训练基于caffe的SSD模型的时候,我们需要将图片数据转 ...

  10. ORM(Object-Relational Mapping 对象关系映射)如何实现(转)

    原文链接:http://blog.163.com/hzd_love/blog/static/13199988120107891854473/ 1.什么是ORM ORM的全称是Object Relati ...