How to display a list of hashmaps in ui:repeat?
Asked Answered
B

1

6

I have a problem using JSF to display some data in Facelets. I have list of hashmaps:

List<Map<String, String>> persons = new LinkedList<Map<String,String>>();

public List getPersons() {
    return this.persons;
}

I get this as follows from database:

while(rs.next()) {
  Map<String,String> result = new HashMap<String,String>();
  result.put("name", rs.getString(1));
  result.put("category", rs.getString(2));
  this.persons.add(result);
}

So, my problem is how to display info for every map in xhtml. I try to used ui:repeat but it is wrong so I need help. I must have getter for name and family but how should I add it?

<ui:repeat value="#{class.persons}" var="persons">   
  <h:outputText value="#{persons['name'}"/>
  <h:outputText value="#{persons['family'}"/>                       
</ui:repeat>

I hope you understand my problem and will help me to fix it. Thanks in advance!

Bugger answered 3/12, 2011 at 1:47 Comment(0)
C
4

The #{persons} is thus a Map<String, String>. You can access map values by keys in the same way as normal Javabeans. So #{person.name} will return map.get("name").

So, this should do:

<ui:repeat value="#{class.persons}" var="person">   
  <h:outputText value="#{person.name}"/>
  <h:outputText value="#{person.family}"/>
</ui:repeat>

(I only renamed persons to person, because it essentially represents only one person)

The following way is by the way also valid and it would actually be the only way if you have a map key which contained periods:

<ui:repeat value="#{class.persons}" var="persons">   
  <h:outputText value="#{persons['name']}"/>
  <h:outputText value="#{persons['family']}"/>                       
</ui:repeat>

(you see, you were close, you only forgot the closing brace)

The normal practice, however, is to create a Javabean class instead of a Map if it actually represents an entity.

public class Person {

    private String name;
    private String family;
    // ...

    // Add/generate getters/setters and other boilerplate.
}

And feed it as List<Person> to the view.

Cataract answered 3/12, 2011 at 3:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.