在速度模板中调用java方法

eat*_*ode 7 templates velocity

我有一个类CurrencyUtil我已经编写了一个方法,convertCurrency(String symbol, long value)我想从速度模板中调用这个方法.我正在放置此类的对象,map.put("formatter", currencyUtil);并在模板中我使用标记,$formatter.convertCurrency($currency, $total)但是当呈现模板时,它不会打印结果.

这里我的问题是,如果java方法和模板中的参数名称相同吗?还是有其他问题吗?

小智 10

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

Example.java

package com.example.currency;

import org.apache.velocity.app.Velocity;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import java.io.*;

public class Example
{
    public Example(String templateFile)
    {
        try
        {

            Velocity.init("velocity.properties");

            VelocityContext context = new VelocityContext();
            CurrencyUtil cu = new CurrencyUtil();
            cu.setCurrencyRate("EUR", 1.25);
            context.put("formatter", cu); 

            Template template =  null;

            try
            {
                template = Velocity.getTemplate(templateFile);
            }
            catch( ResourceNotFoundException rnfe )
            {
                System.out.println("Example : error : cannot find template " + templateFile );
            }
            catch( ParseErrorException pee )
            {
                System.out.println("Example : Syntax error in template " + templateFile + ":" + pee );
            }


            BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(System.out));

            if ( template != null)
                template.merge(context, writer);


            writer.flush();
            writer.close();
        }
        catch( Exception e )
        {
            System.out.println(e);
        }
    }


    public static void main(String[] args)
    {
        Example t = new Example("example.vm");
    }
}
Run Code Online (Sandbox Code Playgroud)

CurrencyUtil.java

package com.example.currency;

import java.util.Map;
import java.util.HashMap;

public class CurrencyUtil {
    private static Map<String, Double> rates = new HashMap<String, Double>();

    public double getCurrencyRate(String symbol){
        return rates.get(symbol);
    }
    public void setCurrencyRate(String symbol, double currencyRate){
        rates.put(symbol, currencyRate);
    }

    public double convertCurrency(String symbol, long value){
        return value * getCurrencyRate(symbol);
    }
}
Run Code Online (Sandbox Code Playgroud)

example.vm

#set( $total = 10000000000)
#set( $currency = "EUR")
$formatter.convertCurrency($currency, $total) 
Run Code Online (Sandbox Code Playgroud)

  • 我做了同样的事情,我的问题是参数类型不匹配.经过这么长时间的回答,谢谢你的回答. (5认同)