2

我尝试从 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]
----------
4

1 回答 1

3

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

在这种情况下,由于您正在results输入root而不是调用mc.getAll()您的 freemarker,您可以使用root

所以

<#list restults as result>

或者您需要使用键将MainService实例添加ms到模型(rootmc

Map<String, Object> root = new HashMap<String, Object>();
root.put("mc", ms);
于 2013-06-26T03:45:11.530 回答