我被困在这个问题上。
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";}
}
.vm
#set($parameter="1")
#set($message = $action.getMessage("$parameter").show())
<td>$message</td>`
在渲染的 HTML 中,我得到 $message
。为什么我没有收到实际消息?
最佳答案
来自 Velocity 文档:
Velocity is just a façade for real Java objects...
因此,要访问 Velocity 模板中类的公共(public)方法,相关类的对象应该对 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")
<小时/>
关于java - 在 Velocity 模板中传递 Java 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40643537/