【问题标题】:Velocity Template is not detempletizing when a field inside object is accessed访问对象内的字段时,速度模板不会去模板化
【发布时间】:2017-05-18 20:47:17
【问题描述】:

我写了下面的代码,基本上需要打印Hello simple Kishore,方法是在模板Hello $string $value.name中替换$string$value.name的值。

它替换了$string 的值,但是$value.name 永远不会被替换。
我尝试对 $value 的值进行去模板化,并且在将 TestClass$Sample@5594a1b5 作为输出时效果很好,所以问题在于 模板无法访问对象中的字段

由于一些限制,我必须使用VelocityEngine.evaluate 本身而不是VelocityEngine.mergeTemplate

代码:

class Sample {
    private String name = "Kishore";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Test {
    public static void main(String args[]) throws Exception {
        String query = "Hello $string $value.name";

        VelocityContext vCtx = new VelocityContext();
        vCtx.put("string","simple");
        vCtx.put("value", new Sample());

        Writer out = new StringWriter();
        VelocityEngine engine = new VelocityEngine();
        engine.init();
        engine.evaluate(vCtx, out, "ERR:", new StringReader(query));

        System.out.println(out.toString());
    }
}

输出:

Hello simple $value.name

【问题讨论】:

    标签: java velocity vtl


    【解决方案1】:

    要解决此问题,您应该为 Sample 类添加 public 修饰符:

    public class Sample {
        ...
    

    【讨论】:

    • 啊,我只是在调试它,发现 ClassMap 类创建所有方法的缓存查找公共修饰符 if Modifier.isPublic(classToReflect.getModifiers())) populateMethodCacheWith(methodCache, classToReflect); 谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多