`
fantasy
  • 浏览: 507234 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Velocity-初体验

    博客分类:
  • web
 
阅读更多

Velocity是什么

Velocity是一个基于java的模板引擎,类似与Freemarker。

为啥要用模板引擎

  • 模板引擎的速度要比jsp快,因为JSP需要编译成servlet。
  • 将数据(Date)和模板(View)分离,让不同的角色只关注自己的部分。

Velocity和Freemarker的比较

  • 功能上:FreeMarker的功能比Velocity多,是Velocity的超集。
  • 使用上:Velocity更加简单和轻量级。

Velocity Template Language (VTL)

基本原则:使用$字符开始的用于得到什么;使用#字符开始的用于作些什么。如下
a) 变量:#set( $foo = "gibbous" ) $moon = $foo
b) 属性:$customer.Address
c) 方法:$customer.getAddress()
注意感叹号!:用来强制把不存在的变量显示为空白,所以强烈建议加上!,如$!message。在Freemarker里也建议这样。
其他的在使用中可以参考文档Velocity学习指南.doc

Velocity的工作原理

三步了解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(); 
//1:构建一个上下文,用来存放数据(date)。 
VelocityContext context = new VelocityContext(); 
context.put( "name", new String("Velocity") ); 
Template template = null; 
try
{ 
   //2:读取模板(View) 
   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(); 
//3:组合(control)数据和模板,最后写到sw里,sw即最终数据。 
template.merge( context, sw ); 

  

我觉得Velocity是由上至下逐行扫描模板,当扫描到占位符(如$和#)的时候,通过JAVA的反射机制(或者cglib直接生成字节码)调用JAVA的属性和方法,生成最终数据。

学习资料

官方网址:http://velocity.apache.org/engine/releases/velocity-1.7/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics