在h:dataTable中使用java.util.Map

JPS*_*JPS 17 datatable jsf hashmap treemap

我需要显示Map使用<h:dataTable>.我的支持bean有Map如下属性:

public class Bean {

    private Map<Integer,String> map; // +getter

    @PostConstruct
    public void init() {
        map = new TreeMap<Integer,String>();
        map.put(1,"Sasi");
        map.put(2,"Pushparaju");
        map.put(3,"Venkat Raman");
        map.put(3,"Prabhakaran");
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在JSF页面中我试图将此Map属性绑定到的value属性<h:dataTable>.

 <h:dataTable border="1" value="#{bean.map}" var="map">
    <h:column id="column1">
        <f:facet name="header">
            <h:outputText value="UserId"></h:outputText>
        </f:facet>
        <h:outputText value="#{map.getKey}"></h:outputText>
    </h:column>
    <h:column id="column2">
        <f:facet name="header">
            <h:outputText value="Email Id"></h:outputText>
        </f:facet>
        <h:outputText value="#{map.getValue}"></h:outputText>
    </h:column>
</h:dataTable>
Run Code Online (Sandbox Code Playgroud)

它给出了错误,getKey并且getValue不存在.我可以理解这不是正确的方法.我如何展示Map使用<h:dataTable>

Bal*_*usC 29

直到即将到来的JSF 2.3,UIData如组件<h:dataTable>,<p:dataTable>等,并<ui:repeat>没有支持通过迭代Map.仅支持此功能<c:forEach>.

一种方法是将映射条目转换为数组(单独entrySet()不起作用,因为在即将到来的JSF 2.3之前UIData也不支持Set).

<h:dataTable value="#{bean.map.entrySet().toArray()}" var="entry">
    <h:column>#{entry.key}</h:column>
    <h:column>#{entry.value}</h:column>
</h:dataTable>
Run Code Online (Sandbox Code Playgroud)

另一种方法是将地图的条目集包装在<h:dataTable>可以迭代的集合中,例如ArrayList.

public class Bean {

    private Map<Integer, String> map;
    private List<Entry<Integer, String>> entries; // +getter (no setter necessary)

    @PostConstruct
    public void init() {
        map = new TreeMap<>();
        map.put(1, "Sasi");
        map.put(2, "Pushparaju");
        map.put(3, "Venkat Raman");
        map.put(4, "Prabhakaran");
        entries = new ArrayList<>(map.entrySet());
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)
<h:dataTable value="#{bean.entries}" var="entry">
    <h:column>#{entry.key}</h:column>
    <h:column>#{entry.value}</h:column>
</h:dataTable>
Run Code Online (Sandbox Code Playgroud)

然而,更干净,自我记录和可重复使用的是List<User>替代,其中User类具有必要的属性idname.

public class Bean {

    private List<User> users; // +getter (no setter necessary)

    @PostConstruct
    public void init() {
        users = new ArrayList<>();
        users.add(new User(1, "Sasi"));
        users.add(new User(2, "Pushparaju"));
        users.add(new User(3, "Venkat Raman"));
        users.add(new User(4, "Prabhakaran"));
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)
<h:dataTable value="#{bean.users}" var="user">
    <h:column>#{user.id}</h:column>
    <h:column>#{user.name}</h:column>
</h:dataTable>
Run Code Online (Sandbox Code Playgroud)