velocity 二 开发篇

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

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

如下的例子:
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


上面的例子使用的是单例模式,可以使用运行期实例:
VelocityEngine ve  =   new  VelocityEngine();
ve.setProperty(
    VelocityEngine.RUNTIME_LOG_LOGSYSTEM, 
this );
ve.init();


关于context
context,类似于map环境,包括两个主要的方法:
public  Object put(String key, Object value);
public  Object get(String key);

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

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

Context chaining,
context支持多个context串,如下:
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不仅可以用于提供模板输出,而且可以直接对字符串进行评估:
StringWriter w  =   new  StringWriter();
Velocity.mergeTemplate(
" testtemplate.vm " , context, w );

String s 
=   " We are using $project $name to render this. " ;
=   new  StringWriter();
Velocity.evaluate( context, w, 
" mystring " , s );



 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值