先来看看velocity是怎么工作的?
在应用中使用velocity,一般需要以下的几个步骤:
如下的例子:
上面的例子使用的是单例模式,可以使用运行期实例:
关于context
context,类似于map环境,包括两个主要的方法:
而默认的VelocityContext是使用map封装,保存相应的变量
当然,如果想和其他环境合并,如FacesContext中的Elcontext,需要定义自己的实现类。
Context chaining,
context支持多个context串,如下:
Velocity不仅可以用于提供模板输出,而且可以直接对字符串进行评估:
在应用中使用velocity,一般需要以下的几个步骤:
- 初始化Velocity,可以使用单例,或者运行期实例
- 创建context对象,用于包括相应的变量
- 在context中增加相应的数据
- 选择模板
- 合并模板,产生输出
如下的例子:
java 代码
- 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(); 1
- VelocityContext context = new VelocityContext(); 2
- context.put( "name", new String("Velocity") ); 3
- Template template = null;
- try
- {
- template = Velocity.getTemplate("mytemplate.vm"); 4
- }
- 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 ); 5
上面的例子使用的是单例模式,可以使用运行期实例:
java 代码
- VelocityEngine ve = new VelocityEngine();
- ve.setProperty(
- VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
- ve.init();
关于context
context,类似于map环境,包括两个主要的方法:
java 代码
- public Object put(String key, Object value);
- public Object get(String key);
而默认的VelocityContext是使用map封装,保存相应的变量
当然,如果想和其他环境合并,如FacesContext中的Elcontext,需要定义自己的实现类。
Context chaining,
context支持多个context串,如下:
java 代码
- VelocityContext context1 = new VelocityContext();
- context1.put("name","Velocity");
- context1.put("project", "Jakarta");
- context1.put("duplicate", "I am in context1");
- VelocityContext context2 = new VelocityContext( context1 );
- context2.put("lang", "Java" );
- context2.put("duplicate", "I am in context2");
- template.merge( context2, writer );
Velocity不仅可以用于提供模板输出,而且可以直接对字符串进行评估:
java 代码
- StringWriter w = new StringWriter();
- Velocity.mergeTemplate("testtemplate.vm", context, w );
- String s = "We are using $project $name to render this.";
- w = new StringWriter();
- Velocity.evaluate( context, w, "mystring", s );