从速度文档:
Velocity 只是真实 Java 对象的一个外观......
因此,要访问 Velocity 模板中类的公共方法,相关类的对象应该对 Velocity 模板可见。
public class MessageSource {
public String getMessage(String id){
log.error("passing parameter "+id+" "+id.getClass().getName());
if(id.compareTo("1")==0){
return "nothing perfect";
} else {
return "All done";
}
}
}
现在公开对象MessageSource
:
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.init();
/* next, get the Template */
Template t = ve.getTemplate( "helloworld.vm" );
/* create a context and add data */
VelocityContext context = new VelocityContext();
context.put("messageSource", new MessageSource());
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* show the World */
System.out.println( writer.toString() );
所以,在你的速度模板中......
$messageSource.getMessage("identifier")