源文件
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:12:38
*
* @author Jonathan Q. Bo
* @version 1.0 valocity study
*/
public class QuickStartExample {
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();
/* 此处采用字符串模版 */
String s = "We are using string velocity to generate $project $name";
/* 进行解析 */
Velocity.evaluate(context,w,"mystring",s);
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 string velocity to generate jonathan's velocity first example