Velocity教程

我们通过一个简单的实例来讲解一下velocity的使用过程

import java.io.StringWriter;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
public class Simple1 {
/**
* 入门,标准velocity的使用
*/
public static void main(String[] args) {
// 创建引擎
VelocityEngine ve = new VelocityEngine();
// 设置模板加载路径,这里设置的是class下
ve.setProperty(Velocity.RESOURCE_LOADER, "class");
ve.setProperty("class.resource.loader.class",
// 即上一句的key.RESOURCE_LOADER的值.class
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
try {
// 进行初始化操作
ve.init();
// 加载模板,设定模板编码
// 这里的gbk不是必须的,但是我的模板中使用了中文所以要指定编码规则。
Template t = ve.getTemplate("test/velocity/simple1.vm", "gbk");
// 也可以使用Velocity.setProperty
(Velocity.FILE_RESOURCE_LOADER_PATH, loadpath);
// loadpath是路径地址
// 设置初始化数据
VelocityContext context = new VelocityContext();
context.put("name", "张三");
context.put("project", "Jakarta");
// 设置输出
StringWriter writer = new StringWriter();
// 将环境数据转化输出
t.merge(context, writer);
// 简化操作
// ve.mergeTemplate("test/velocity/simple1.vm", "gbk", context, writer );
System.out.println(writer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}


## 第一个例子
你好 $name !
$project project.



velocity虽然已经为我们提供了一些资源加载器,基本已经可以满足大部分的用户需求。有的时候还需要我们必须手动去写一些,比如:我们打算采用 String的模板而不是vm文件形式,为的是将模板存入db中。
这是我们只需要继承org.apache.velocity.runtime.resource.ResourceLoader 并实现我们想要的功能。
下面的例子就是拿上面的需求来进行一个简单的实现。

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;

public class MyResourceLoader extends ResourceLoader {
public long getLastModified(Resource arg0) {
return 0;
}

public InputStream getResourceStream(String arg0)
throws ResourceNotFoundException {
InputStream result = null;
if (arg0 == null || arg0.length() == 0) {
throw new ResourceNotFoundException("模板没有被定义~!");
}
result = new ByteArrayInputStream(arg0.getBytes());
return result;
}

public void init(ExtendedProperties arg0) {
}

public boolean isSourceModified(Resource arg0) {
return false;
}
}

// 修改如下几行
ve.setProperty(Velocity.RESOURCE_LOADER, "str");
ve.setProperty("str.resource.loader.class",
"test.velocity.MyResourceLoader");
Template t = ve.getTemplate("你好 $name!\r\n$project project", "gbk");



其他功能展示
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.DateTool;

public class Simple3 {
public static void main(String[] args) {
try {
Velocity.init("src/velocity.properties");
VelocityContext context = new VelocityContext();
// 历遍集合/数组
context.put("list", Arrays.asList("第一个", "第二个", "第三个"));
// 历遍Map集合
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
context.put("map", map);
// 判断分支
context.put("flag", true);
// 格式化日期
context.put("now", new Date());
context.put("dateformat", new DateTool());
// NUll处理 输出 $title
context.put("title", null);
Template template = Velocity.getTemplate("src/template.vm");
StringWriter sw = new StringWriter();
template.merge(context, sw);
sw.flush();
System.out.println(sw.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}


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

#foreach($key in $map.keySet())
$key = $map.get($key)
$velocityCount > $key=$map.get($key)
#end

#*
velocityCount 变量名可以通过directive.foreach.counter.name属性修改,
如:directive.foreach.counter.name =index,以后可以通过$index进行访问。
迭代的索引默认从1开始,我们可以通过directive.foreach.counter.initial.value=0进行修改。
*#

##在模版中进行赋值
#set($name="xace")
$name
#set($condition=true)
$condition
#set($ints = [1..10])
#foreach($entry in $ints)
$entry
#end
#set($strs = ["一","二","三"])
#foreach($entry in $strs)
$entry
#end


#if($flag) 成立
#else 不成立
#end

$dateformat.format("yyyy-MM-dd", $now)

$title



velocity.properties
[quote]#指定日志文件存放位置
runtime.log = E:\\spring\\velocity\\velocity_example.log
#指定模版文件加载位置
file.resource.loader.path=E:\\spring\\velocity
#指定输入编码格式
input.encoding=UTF-8
#指定velocity的servlet向浏览器输出内容的编码
default.contentType=text/html; charset\=UTF-8
#指定输出编码格式
output.encoding=UTF-8[/quote]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值