gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:27 24 4
gpt4 key购买 nike

我有以下 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> :

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 [在第 9 行第 69 列的模板“history.ftl”中]

为什么?

最佳答案

有这样一个mail list request允许访问公共(public)字段解决方案是使用方法 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 迭代对象的 ArrayList 并访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48672378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com