views:

59

answers:

2

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 ?

+4  A: 

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.

Bozho
I think he's not using Facelets since he explicitly tagged JSP.
BalusC
sometimes they tag so just because a `.jsp` extension is used (with facelets inside) :)
Bozho
actualy I am using facelets, but any good solution will do
Vitaly Polonetsky
@BalusC - see :) my sixth sense worked :)
Bozho
@Vitaly Polonetsky use `ui:repeat` and use the inner part from BalusC's answer
Bozho
+2  A: 

Use JSTL c:forEach (just drop jstl-1.2.jar in /WEB-INF/lib to install it, if not done yet). You can use LoopTagStatus#isLast() to determine if the currently iterated item is the last item and if so, then omit the comma.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<c:forEach items="#{listHolder.lst}" var="someObj" varStatus="loop">
    ${someObj.name}${!loop.last ? ', ' : ''}
</c:forEach>

Update: since you're actually using Facelets, here's a Facelets targeted answer:

<html xmlns:ui="http://java.sun.com/jsf/facelets"&gt;
...
<ui:repeat value="#{listHolder.lst}" var="someObj" varStatus="loop">
    #{someObj.name}#{!loop.last ? ', ' : ''}
</ui:repeat>

But you should really accept Bozho's answer since he was first and his sixth sense has it right ;)

BalusC