In JSF what is the shortest way to output List as comma separated list of “name” properties of SomeObj

前端 未结 3 1911
星月不相逢
星月不相逢 2020-12-11 02:16

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;
  ...         


        
相关标签:
3条回答
  • 2020-12-11 02:31

    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:

    • How iterate over List<T> and render each item in JSF Facelets
    • JSTL in JSF2 Facelets... makes sense?
    0 讨论(0)
  • 2020-12-11 02:43

    If you can't use varStatus because you're stuck with using JSF 1.2, you can do:

    <ui:repeat value="#{listHolder.lst}" var="someObj">#{someObj != listHolder.lst[0] ? ',' : ''}
    #{someObj.name}</ui:repeat>
    

    The absence of whitespace around the EL-expressions is deliberate, we don't want a space to appear there in the rendered HTML.

    0 讨论(0)
  • 2020-12-11 02:44

    use <ui:repeat> (from facelets). It's similar to c:forEach

    Or pre-compute the comma-separated string in the managed bean, and obtain it via a getter.

    0 讨论(0)
提交回复
热议问题