我尝试从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]
----------
答案 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);