Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Templates 在velocity模板中调用java方法_Templates_Velocity - Fatal编程技术网

Templates 在velocity模板中调用java方法

Templates 在velocity模板中调用java方法,templates,velocity,Templates,Velocity,我有一个类CurrencyUtil,其中我编写了一个方法convertCurrency(字符串符号,长值)我想从velocity模板调用这个方法。我正在放置这个类的对象map.put(“格式化程序”,currencyUtil)在模板中,我将标记用作$formatter.convertCurrency($currency,$total),但在呈现模板时,它不会打印结果 这里我的问题是,java方法和模板中的参数名是否应该相同?或者还有其他问题吗?java方法和模板中的参数名称可能不同。您可以尝试使

我有一个类
CurrencyUtil
,其中我编写了一个方法
convertCurrency(字符串符号,长值)
我想从velocity模板调用这个方法。我正在放置这个类的对象
map.put(“格式化程序”,currencyUtil)在模板中,我将标记用作
$formatter.convertCurrency($currency,$total)
,但在呈现模板时,它不会打印结果


这里我的问题是,java方法和模板中的参数名是否应该相同?或者还有其他问题吗?

java方法和模板中的参数名称可能不同。您可以尝试使用以下示例查找问题

Example.java

package com.example.currency;
导入org.apache.velocity.app.velocity;
导入org.apache.velocity.VelocityContext;
导入org.apache.velocity.Template;
导入org.apache.velocity.exception.ParseErrorException;
导入org.apache.velocity.exception.ResourceNotFoundException;
导入java.io.*;
公开课范例
{
公共示例(字符串模板文件)
{
尝试
{
Velocity.init(“Velocity.properties”);
VelocityContext上下文=新的VelocityContext();
CurrencyUtil cu=新的CurrencyUtil();
cu.固定汇率(“欧元”,1.25);
context.put(“格式化程序”,cu);
模板模板=null;
尝试
{
template=Velocity.getTemplate(templateFile);
}
捕获(ResourceNotFoundException rnfe)
{
System.out.println(“示例:错误:找不到模板”+模板文件);
}
捕获(ParseErrorException pee)
{
System.out.println(“示例:模板“+templateFile+”:“+pee”中的语法错误);
}
BufferedWriter=新的BufferedWriter(
新的OutputStreamWriter(System.out));
如果(模板!=null)
合并(上下文、编写器);
writer.flush();
writer.close();
}
捕获(例外e)
{
系统输出打印ln(e);
}
}
公共静态void main(字符串[]args)
{
示例t=新示例(“Example.vm”);
}
}
CurrencyUtil.java

package com.example.currency;
导入java.util.Map;
导入java.util.HashMap;
公共类CurrencyUtil{
私有静态映射速率=新HashMap();
公共双getCurrencyRate(字符串符号){
返回率。获取(符号);
}
public void setCurrencyRate(字符串符号,双currencyRate){
汇率。看跌期权(符号,货币汇率);
}
公共双货币(字符串符号,长值){
返回值*getCurrencyRate(符号);
}
}
示例.vm

#套($total=1000000000)
#设置($currency=“EUR”)
$formatter.convertCurrency($currency,$total)

Velocity以
字符串的形式接收所有参数。在函数中,您收到一个
字符串
并应用强制转换。

我做了同样的事情,我的问题是参数类型不匹配。谢谢你这么长时间后的回答。eatSleepCode对apatian回答的评论也解决了我的问题。所以,这也可能对其他人有所帮助:我的问题是参数类型不匹配。