在Velocity模板中传递Java函数

在Velocity模板中传递Java函数,java,velocity,vtl,Java,Velocity,Vtl,我被困在这上面了 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”) #s

我被困在这上面了

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())
$message`
在呈现的HTML中,我得到
$message
。为什么我没有得到真正的信息

你们不能直接以速度传递函数

Test.java Message.java example.vm
#set($parameter=“1”)
#set($message=$formatter.message($parameter))
$message
你们不能直接以速度传递函数

Test.java Message.java example.vm
#set($parameter=“1”)
#set($message=$formatter.message($parameter))
$message

来自Velocity文档:

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")


来自Velocity文档:

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")


do“1”。equals(id)代替nothing改为“1”。equals(id)代替nothing改为“1”。回答好,但需要解释。回答好,但需要解释。
$messageSource.getMessage("identifier")