本文共 1258 字,大约阅读时间需要 4 分钟。
译者:方腾飞
基本模式
当你在一个应用程序或者一个servlet里,或者在其他任何一个地方使用Velocity时,通常按照如下方式处理:
在代码里通过org.apache.velocity.app.Velocity类使用单例模式,代码如下:
import java.io.StringWriter;import org.apache.velocity.VelocityContext;import org.apache.velocity.Template;import org.apache.velocity.app.Velocity;import org.apache.velocity.exception.ResourceNotFoundException;import org.apache.velocity.exception.ParseErrorException;import org.apache.velocity.exception.MethodInvocationException;Velocity.init();VelocityContext context = new VelocityContext();context.put( "name", new String("Velocity") );Template template = null;try{ template = Velocity.getTemplate("mytemplate.vm");}catch( ResourceNotFoundException rnfe ){ // couldn't find the template}catch( ParseErrorException pee ){ // syntax error: problem parsing the template}catch( MethodInvocationException mie ){ // something invoked in the template // threw an exception}catch( Exception e ){}StringWriter sw = new StringWriter();template.merge( context, sw );
这是个基本的模式,它非常简单,不是吗?当你使用Velocity渲染一个模板的时候,通常会发生什么。你可能不会完全像这样写代码,所以我们提供几个工具类帮助你写代码。然而, 无论如何,按照上面的序列使用Velocity,它向我们展示了台前幕后发生了什么。
转载地址:http://qbzel.baihongyu.com/