Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

facelets - In JSF what is the shortest way to output List<SomeObj> as comma separated list of "name" properties of SomeObj

I have a question about outputing a list of objects as a comma separated list in JSF.

Let's say:

public class SomeObj {
  private String name;
  ... constructors, getters and setters ...
}

and List<SomeObj>:

List<SomeObj> lst = new ArrayList<SomeObj>();
lst.add(new SomeObj("NameA"));
lst.add(new SomeObj("NameB"));
lst.add(new SomeObj("NameC"));

to output it as a listbox I can use this code:

<h:selectManyListbox id="id1"
                  value="#{listHolder.selectedList}">
  <s:selectItems value="#{listHolder.lst}"
                   var="someObj"
                 label="#{someObj.name}"/>
  <s:convertEntity />
</h:selectManyListbox>

But what is the easiest way to output the list as is, comma seperated ? Like this:

NameA, NameB, NameC

Should I use JSTL <c:forEach/> or may be the <s:selectItems/> tag can also be used ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Given a List<Person> persons where Person has a name property,

  • If you're already on Java EE 7 with EL 3.0, then use EL stream API.

    #{bean.persons.stream().map(p -> p.name).reduce((p1, p2) -> p1 += ', ' += p2).get()}
    
  • If you're not on EL 3.0 yet, but have JSF 2.x at hands, then use Facelets <ui:repeat>.

    <ui:repeat value="#{bean.persons}" var="person" varStatus="loop">
        #{person.name}#{not loop.last ? ', ' : ''}
    </ui:repeat>
    
  • Or if you're still on jurassic JSP, use JSTL <c:forEach>.

    <c:forEach items="#{bean.persons}" var="person" varStatus="loop">
        ${person.name}${not loop.last ? ', ' : ''}
    </c:forEach>
    

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...