ITeye博客

velocity 二 开发篇

zyl · 2007-05-17 07:30 · web framework · Markdown

先来看看velocity是怎么工作的?

在应用中使用velocity,一般需要以下的几个步骤:

  • 初始化Velocity,可以使用单例,或者运行期实例
  • 创建context对象,用于包括相应的变量
  • 在context中增加相应的数据
  • 选择模板
  • 合并模板,产生输出

如下的例子:

java 代码

 

  1. import java.io.StringWriter;
  2. import org.apache.velocity.VelocityContext;
  3. import org.apache.velocity.Template;
  4. import org.apache.velocity.app.Velocity;
  5. import org.apache.velocity.exception.ResourceNotFoundException;
  6. import org.apache.velocity.exception.ParseErrorException;
  7. import org.apache.velocity.exception.MethodInvocationException;
  8. Velocity.init();                            1
  9. VelocityContext context = new VelocityContext();    2
  10. context.put( "name", new String("Velocity") );        3
  11. Template template = null;
  12. try
  13. {
  14. template = Velocity.getTemplate("mytemplate.vm");    4
  15. }
  16. catch( ResourceNotFoundException rnfe )
  17. {
  18. // couldn't find the template
  19. }
  20. catch( ParseErrorException pee )
  21. {
  22. // syntax error: problem parsing the template
  23. }
  24. catch( MethodInvocationException mie )
  25. {
  26. // something invoked in the template
  27. // threw an exception
  28. }
  29. catch( Exception e )
  30. {}
  31. StringWriter sw = new StringWriter();
  32. template.merge( context, sw );                5

上面的例子使用的是单例模式,可以使用运行期实例:

java 代码

 

  1. VelocityEngine ve = new VelocityEngine();
  2. ve.setProperty(
  3. VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
  4. ve.init();

关于context
context,类似于map环境,包括两个主要的方法:

java 代码

 

  1. public Object put(String key, Object value);
  2. public Object get(String key);

而默认的VelocityContext是使用map封装,保存相应的变量

当然,如果想和其他环境合并,如FacesContext中的Elcontext,需要定义自己的实现类。

Context chaining,
context支持多个context串,如下:

java 代码

 

  1. VelocityContext context1 = new VelocityContext();
  2. context1.put("name","Velocity");
  3. context1.put("project", "Jakarta");
  4. context1.put("duplicate", "I am in context1");
  5. VelocityContext context2 = new VelocityContext( context1 );
  6. context2.put("lang", "Java" );
  7. context2.put("duplicate", "I am in context2");
  8. template.merge( context2, writer );

Velocity不仅可以用于提供模板输出,而且可以直接对字符串进行评估:

java 代码

 

  1. StringWriter w = new StringWriter();
  2. Velocity.mergeTemplate("testtemplate.vm", context, w );
  3. String s = "We are using $project $name to render this.";
  4. w = new StringWriter();
  5. Velocity.evaluate( context, w, "mystring", s );

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。