闲人野居
好好学习,天天向上
posts - 57,  comments - 137,  trackbacks - 0
先来看看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 );



posted on 2007-05-17 07:34 布衣郎 阅读(3833) 评论(0)  编辑  收藏 所属分类: web view技术

只有注册用户登录后才能发表评论。


网站导航:
 

<2007年5月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

常用链接

留言簿(12)

随笔分类(59)

随笔档案(57)

blog

java

uml

搜索

  •  

积分与排名

  • 积分 - 355562
  • 排名 - 154

最新评论

阅读排行榜

评论排行榜