Velocity 1.7之简单实例




上面是velocity的官网解释  感觉自己翻译总是不到位  所以直接贴英文算了  记录学习的脚步

下面看看一个简单的示意  演示了velocity的基本特性



 需要上面的三个jar包 

测试代码 VelocityTest.java

package com.undergrowth.velocity;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class VelocityTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("===============simpleVelocity1测试,使用输出流作为writer=====================");
		simpleVelocity1();
		System.out.println("===============simpleVelocity1测试,使用输出流作为writer=====================");
		System.out.println("===============simpleVelocity2测试,使用字符串输出流作为writer=====================");
		simpleVelocity2();
		System.out.println("===============simpleVelocity2测试,使用字符串输出流作为writer=====================");
		System.out.println("===============simpleVelocity3测试,使用字符串作为模板,字符串输出流作为writer=====================");
		simpleVelocity3();
		System.out.println("===============simpleVelocity3测试,使用字符串作为模板,字符串输出流作为writer=====================");
	}

	//使用输入字符串作为模板
	private static void simpleVelocity3() {
		// TODO Auto-generated method stub
		String strVelocity="显示 $project 名称";
		VelocityContext context=new VelocityContext();
		context.put("project", VelocityTest.class.getName());
		StringWriter writer=new StringWriter();
		Velocity.evaluate(context, writer, "输入字符串作为模板", strVelocity);
		System.out.println(writer);
	}

	//简单测试2
	private static void simpleVelocity2() {
		// TODO Auto-generated method stub
		//改变velocity资源的查找路径
		VelocitySimple velocitySimple=new VelocitySimple();
		VelocityContext vcContext=velocitySimple.createVelocityContext();
		//使用字符串输出流
		StringWriter writer=new StringWriter();
		Velocity.mergeTemplate("velocity.vm", "utf-8", vcContext, writer);
		System.out.println(writer);
	}

	//简单测试1
	private static void simpleVelocity1() {
		VelocitySimple velocitySimple=new VelocitySimple();
		VelocityContext vcContext=velocitySimple.createVelocityContext();
		//使用控制台作为输出流
		BufferedWriter writer=velocitySimple.createBufferedWriter();
		Template template=velocitySimple.createTemplate("velocity.vm");
		template.merge(vcContext, writer);
		try {
			writer.flush();
			//这里如果正式开发的话 需要将输出流关闭 但是因为这里选择是控制台 如果关闭的话 后面的测试方式的输出信息就没有了
			//writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

velocity的封装类VelocitySimple.java

package com.undergrowth.velocity;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class VelocitySimple {
	
	public VelocitySimple(){
		//如果不修改velocity的资源查找路径的话  即要将模板文件放在项目的目录下 即和src属于一个目录级别
		changeVelocityResourceLoaderPath();
	}

	//改变Velocity查找资源的路径
	private void changeVelocityResourceLoaderPath() {
		//设定查找资源的路径为类加载器的路径  即src下面
		String pathResources=VelocitySimple.class.getClassLoader().getResource("./").getPath();
		VelocityEngine velocityEngine=new VelocityEngine();
		Properties properties=new Properties();
		properties.setProperty(velocityEngine.FILE_RESOURCE_LOADER_PATH, pathResources);
		//使用默认配置和自己定义的配置文件初始化velocity引擎
		Velocity.init(properties);
	}
	
	//1.创建上下文 填充数据
	public VelocityContext createVelocityContext(){
		VelocityContext vcContext=new VelocityContext();
		//填充一个listData列表和className变量的数据
		vcContext.put("listData", getListData());
		vcContext.put("className", VelocitySimple.class.getName());
		return vcContext;
	}

	//2.根据外部摸板 创建模板对象
	public Template createTemplate(String pathTemplate){
		Template template=null;
		//此时的资源查找 即是在changeVelocityResourceLoaderPath()设置的路径下
		template=Velocity.getTemplate(pathTemplate, "utf-8");
		return template;
	}
	
	//3.创建输出流 即将模板合并后输出到哪个地方
	public BufferedWriter createBufferedWriter(){
		BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(System.out));
		return writer;
	}
	
	//获取封装数据
	private ArrayList getListData() {
		// TODO Auto-generated method stub
		ArrayList<String> alArrayList=new ArrayList<String>();
		alArrayList.add("java语言");
		alArrayList.add("c语言");
		alArrayList.add("c++语言");
		alArrayList.add("c#语言");
		return alArrayList;
	}
	
}


模板文件 velocity.vm

这是一个$className实例,显示简单的Velocity

References begin with $ and are used to get something. Directives begin with # and are used to do something.
Velocity engine  resolve  context object's  data then  replace in the template ,result output the write

#set($this="Velocity")
$this 很好用

#foreach($name in $listData)
	$name
#end

#set($condition=true)	

#if($condition)
	条件为真
#else
	条件为假
#end	

控制台输出结果

===============simpleVelocity1测试,使用输出流作为writer=====================
这是一个com.undergrowth.velocity.VelocitySimple实例,显示简单的Velocity

References begin with $ and are used to get something. Directives begin with # and are used to do something.
Velocity engine  resolve  context object's  data then  replace in the template ,result output the write

Velocity 很好用

	java语言
	c语言
	c++语言
	c#语言


	条件为真
	===============simpleVelocity1测试,使用输出流作为writer=====================
===============simpleVelocity2测试,使用字符串输出流作为writer=====================
这是一个com.undergrowth.velocity.VelocitySimple实例,显示简单的Velocity

References begin with $ and are used to get something. Directives begin with # and are used to do something.
Velocity engine  resolve  context object's  data then  replace in the template ,result output the write

Velocity 很好用

	java语言
	c语言
	c++语言
	c#语言


	条件为真
	
===============simpleVelocity2测试,使用字符串输出流作为writer=====================
===============simpleVelocity3测试,使用字符串作为模板,字符串输出流作为writer=====================
显示 com.undergrowth.velocity.VelocityTest 名称
===============simpleVelocity3测试,使用字符串作为模板,字符串输出流作为writer=====================

可能出的问题

Exception in thread "main" org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'velocity.vm'
	at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
	at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
	at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
	at org.apache.velocity.runtime.RuntimeSingleton.getTemplate(RuntimeSingleton.java:317)
	at org.apache.velocity.app.Velocity.getTemplate(Velocity.java:378)
	at com.undergrowth.velocity.VelocitySimple.createTemplate(VelocitySimple.java:44)
	at com.undergrowth.velocity.VelocityTest.simpleVelocity1(VelocityTest.java:58)
	at com.undergrowth.velocity.VelocityTest.main(VelocityTest.java:19)

即是找不到模板文件   解决办法

//如果不修改velocity的资源查找路径的话  即要将模板文件放在项目的目录下 即和src属于一个目录级别

或者使用上面的


//改变Velocity查找资源的路径
	private void changeVelocityResourceLoaderPath() {
		//设定查找资源的路径为类加载器的路径  即src下面
		String pathResources=VelocitySimple.class.getClassLoader().getResource("./").getPath();
		VelocityEngine velocityEngine=new VelocityEngine();
		Properties properties=new Properties();
		properties.setProperty(velocityEngine.FILE_RESOURCE_LOADER_PATH, pathResources);
		//使用默认配置和自己定义的配置文件初始化velocity引擎
		Velocity.init(properties);
	}


参考 http://blog.csdn.net/foart/article/details/5084010


原文地址:https://www.cnblogs.com/liangxinzhi/p/4275571.html