package com.velocity.test;
import java.io.StringWriter;
import java.util.Properties;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
/**
*
*/
public class LoaderFromFile {
public static void main(String[] args) throws Exception{
//初始化参数
Properties properties=new Properties();
//设置velocity资源加载方式为class
properties.setProperty("resource.loader", "file");
//设置velocity资源加载方式为file时的处理类
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,
this.getClass().getResource("/").toString().replaceAll("^file:/", "").replaceAll("classes","vm"));
//实例化一个VelocityEngine对象
VelocityEngine velocityEngine=new VelocityEngine(properties);
//实例化一个VelocityContext
VelocityContext context=new VelocityContext();
//向VelocityContext中放入键值
context.put("username", "张三");
context.put("password", "123456789");
context.put("age", "20");
context.put("address", "陕西西安");
context.put("blog", "http://blogjava.net/sxyx2008");
//实例化一个StringWriter
StringWriter writer=new StringWriter();
Template template =velocityEngine.getTemplate("122_add.vm");
template.merge(context, writer);
System.out.println(writer);
//velocityEngine.mergeTemplate("hello.vm", "gbk", context, writer);
System.out.println(writer.toString());
}
}
import java.io.StringWriter;
import java.util.Properties;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
/**
* 从file(文件)中加载模板文件
*122_add.vm在web-inf/vm/文件夹中
* @author welcome*
*/
public class LoaderFromFile {
public static void main(String[] args) throws Exception{
//初始化参数
Properties properties=new Properties();
//设置velocity资源加载方式为class
properties.setProperty("resource.loader", "file");
//设置velocity资源加载方式为file时的处理类
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,
this.getClass().getResource("/").toString().replaceAll("^file:/", "").replaceAll("classes","vm"));
//实例化一个VelocityEngine对象
VelocityEngine velocityEngine=new VelocityEngine(properties);
//实例化一个VelocityContext
VelocityContext context=new VelocityContext();
//向VelocityContext中放入键值
context.put("username", "张三");
context.put("password", "123456789");
context.put("age", "20");
context.put("address", "陕西西安");
context.put("blog", "http://blogjava.net/sxyx2008");
//实例化一个StringWriter
StringWriter writer=new StringWriter();
Template template =velocityEngine.getTemplate("122_add.vm");
template.merge(context, writer);
System.out.println(writer);
//velocityEngine.mergeTemplate("hello.vm", "gbk", context, writer);
System.out.println(writer.toString());
}
}