尝试在Freemarker中调用java方法时,表达式是未定义的

时间:2013-06-26 03:40:40

标签: java freemarker

我尝试从Freemarker模板调用java方法:

我的数据类:

public class SimpleObject {

    private String id;
    private String name;
    public SimpleObject(String id, String name) {
        setId(id);
        setName(name);
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

我的服务类:

public class MainService {

    List<SimpleObject> getAll() {
        SimpleObject so = new SimpleObject("1", "Maksim");
        List<SimpleObject> sol = new ArrayList<SimpleObject>();
        sol.add(so);
        return sol;
    }
}

转换代码:

MainService ms = new MainService();
Map<String, Object> root = new HashMap<String, Object>();
root.put("results", ms.getAll());
StringWriter out = new StringWriter();
Configuration cfg = new Configuration();
cfg.setObjectWrapper(new DefaultObjectWrapper());
Template temp = cfg.getTemplate(".test.ftl");
temp.process(root, out);
System.out.println(out.getBuffer().toString());

.test.ftl

<#list mc.getAll() as result>

  result.getName()

</#list>

错误:

Expression mc is undefined on line 3, column 8 in .test.ftl.
The problematic instruction:
----------
==> list mc.getAll() as result [on line 3, column 1 in .test.ftl]
----------

1 个答案:

答案 0 :(得分:2)

这是因为在您的模型中root没有mc

在这种情况下,由于您将results放入root而不是在自由标记中调用mc.getAll(),因此可以使用root

所以

<#list restults as result>

或者您需要使用密钥MainService

ms实例root添加到模型(mc
Map<String, Object> root = new HashMap<String, Object>();
root.put("mc", ms);