先來看看velocity是怎么工作的?
在應(yīng)用中使用velocity,一般需要以下的幾個(gè)步驟:
- 初始化Velocity,可以使用單例,或者運(yùn)行期實(shí)例
- 創(chuàng)建context對(duì)象,用于包括相應(yīng)的變量
- 在context中增加相應(yīng)的數(shù)據(jù)
- 選擇模板
- 合并模板,產(chǎn)生輸出
如下的例子:
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
上面的例子使用的是單例模式,可以使用運(yùn)行期實(shí)例:
VelocityEngine ve = new VelocityEngine();
ve.setProperty(
VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
ve.init();
關(guān)于context
context,類似于map環(huán)境,包括兩個(gè)主要的方法:
public Object put(String key, Object value);
public Object get(String key);
而默認(rèn)的VelocityContext是使用map封裝,保存相應(yīng)的變量
當(dāng)然,如果想和其他環(huán)境合并,如FacesContext中的Elcontext,需要定義自己的實(shí)現(xiàn)類。
Context chaining,context支持多個(gè)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不僅可以用于提供模板輸出,而且可以直接對(duì)字符串進(jìn)行評(píng)估:
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 );
posted on 2007-05-17 07:34
布衣郎 閱讀(3858)
評(píng)論(0) 編輯 收藏 所屬分類:
web view技術(shù)