先来看看velocity是怎么工作的?
在应用中使用velocity,一般需要以下的几个步骤:
- 初始化Velocity,可以使用单例,或者运行期实例
- 创建context对象,用于包括相应的变量
- 在context中增加相应的数据
- 选择模板
- 合并模板,产生输出
如下的例子:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
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
上面的例子使用的是单例模式,可以使用运行期实例:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
VelocityEngine ve
=
new
VelocityEngine();
ve.setProperty(
VelocityEngine.RUNTIME_LOG_LOGSYSTEM,
this
);
ve.init();
关于context
context,类似于map环境,包括两个主要的方法:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
public
Object put(String key, Object value);
public
Object get(String key);
而默认的VelocityContext是使用map封装,保存相应的变量
当然,如果想和其他环境合并,如FacesContext中的Elcontext,需要定义自己的实现类。
Context chaining,
context支持多个context串,如下:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
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不仅可以用于提供模板输出,而且可以直接对字符串进行评估:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
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 );
转:http://www.blogjava.net/zyl/archive/2007/05/17/117957.html