java-Freemarker迭代对象的ArrayList并访问变量?

我有以下POJO类:

public final class Item
{
    public final long id;
    public final String hash;

    public Item(long _id, String _hash)
    {
        id = _id;
        hash = _hash;
    }
}

我有一个ArrayList< Item&gt ;:

ArrayList<Item> list = new ArrayList<>();
list.add(new Item(1, "abc"));
list.add(new Item(2, "def"));

该列表已添加到模板中:

MODEL.addAttribute("history_list", list);

模板成功遍历列表,插入了一个项目,但是没有获得单个项目的属性:

<#list history_list as row>
     <p>${row.hash}</p>
<#else>
     no items here
</#list>

错误:
    以下内容评估为空或丢失:
    ==> row.hash [在模板“ history.ftl”中,第9行,第69列]

为什么?

解决方法:

曾经有mail list request允许访问公共领域
解决方法是使用方法setExposeFields

DefaultObjectWrapper wrapper = new DefaultObjectWrapper(); 
wrapper.setExposeFields(true); 
FreeMarkerCfg.setObjectWrapper(wrapper); 

freemarker docs中对此进行了解释

If you call setExposeFields(true) on a BeansWrapper instance, it will also expose public, non-static fields of classes as hash keys and values. I.e. if foo is a public, non-static field of the class Bar, and bar is a template variable wrapping an instance of Bar, then bar.foo expression will evaluate as the value of the field foo of the bar object. The public fields in all superclasses of the class are also exposed.

上一篇:java-在不同时区的Freemarker打印日期


下一篇:java-绕过FreeMarker缓存?