源文件
package nc.jonathan.velocity;
import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
/**
*<p> 第二个velocity学习类 </p>
*
*<p> 采用默认初始化设置,解析默认位置模版, 输出到字符串</p>
*
* Create on 2006-4-3 10:49:41
*
* @author Jonathan Q. Bo
* @version 1.0 valocity study
*/
public class SecondExample {
public static void main(String[] args){
try {
/* 初始化运行时引擎, 默认初始化 */
Velocity.init();
/* 建立context, 并放入数据*/
VelocityContext context = new VelocityContext();
context.put("project","jonathan's velocity");
context.put("name","first example");
/* 解析后数据的输出目标,java.io.Writer的子类 */
StringWriter w = new StringWriter();
/* 进行解析 */
//Velocity.mergeTemplate("secondtemplate.vm",context,w);
Velocity.mergeTemplate("secondtemplate.vm","gb2312",context,w);
System.out.println(w);
} catch (ResourceNotFoundException e1) {
System.out.println("## 源文件不存在!");
e1.printStackTrace();
} catch (ParseErrorException e2) {
System.out.println("## 解析文件错误!");
e2.printStackTrace();
} catch (MethodInvocationException e3) {
System.out.println("## 方法调用异常!");
e3.printStackTrace();
} catch (Exception e4){
System.out.println("## 其他错误!");
e4.printStackTrace();
}
}
}
模板文件
We are using template.vm to generate $project $name
输出结果
We are using template.vm to generate jonathan's velocity first example