2

我正在尝试遍历 Map 项的列表,即 HashMaps 的 ArrayList 或类似的东西,并且我正在尝试在 primefaces 数据表中执行此操作。这基本上是我想要做的:

<body>
    <h:form>
        <p:dataTable value="#{customerBean.list}" var="map">
            <c:forEach items="#{map}" var="entry">
                <p:column headerText="#{entry.key}">
                    #{entry.value}
                </p:column>
            </c:forEach>
        </p:dataTable>
    </h:form>
</body>

在这种情况下,customerBean.listis aList<Map<String, String>>并且 entry 是 a Map<String, String>

我想要做的是根据一段时间内的条目数量创建动态数量的列,Map<String, String>使用映射条目的键作为标题名称,并将值作为输出。c:forEach当我使用硬编码时,这件事似乎工作正常Map<String, String>,但显然它不能循环遍历p:dataTable. 我假设程序采取了预防措施,以避免遍历不同大小的地图。那么我怎样才能使这项工作呢?如何根据地图中的条目数量创建任意数量的列?请注意,我 100% 确定Map<String, String>在我的List<Map<String, String>>

编辑:

这是我的 bean 来源。代码工作正常,一切正常,问题只是循环不愿意通过我的地图:

@ManagedBean
@SessionScoped
public class CustomerBean {

    private List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    private Mapper mapper = new Mapper();

    public CustomerBean() {
        list = mapper.all(); //gets data from database
    }

    public List<Map<String, String>> getList() { 
        return list;
    }

    public void setList(List<Map<String, String>> list) { 
        this.list = list;
    } 
}
4

1 回答 1

5

The problem is unrelated to the Map usage in this context. The problem is that you're trying to get a #{map} variable that's only available when view is being rendered, but you're relying on its value at the moment when view is being built. The latter is performed on an earlier lifecycle phase, so it is basically unavailable when you demand it.

Still, tag handler, or view build tag, like <c:forEach>, is the only way to populate the variable number of columns, as <p:column> is assessed when component tree is being built.

Another thing worth noting is that the backing bean bound to <c:forEach> tag's property, such as items, must be anything but view scoped, like request scoped, otherwise it will be recreated upon every request which will bring unexpected/undesired results, as the demanded bean is not there when you try to access its properties. There are some other setup constellations solving this issue, but they're not the subject of discussion here.

<p:dataTable value="#{customerBean.list}" var="map">
    <c:forEach items="#{forEachBean.columnsMap}" var="entry">
        <p:column headerText="#{entry.key}">
            #{map[entry.key]}
        </p:column>
    </c:forEach>
</p:dataTable>

Also worth noting that there is a helper <p:columns> component that does roughly the same.

于 2013-05-22T11:44:01.997 回答