“for” cycle in JSF

青春壹個敷衍的年華 提交于 2020-01-24 02:53:05

问题


I simply need to perform a very basic for cycle in JSF/ICEFaces, basically rendering column numbers

Something like the following pseudo-code

for(int i=0; i<max; i++)
{
   <td>#{i}</td>
}

the <c:forEach> tag iterates over collections, but I don't want to make my backing bean more complex returning a stupid collection of integers.

Do you know a shorter and smarter way?

Thank you


回答1:


The <ui:repeat> tag is what you should really use. The JSTL tags operate outside of the JSF Lifecycle. Cay Horstman has a JSF coursewhich discusses this fact: ui:repeat and Handling Variable-Length Data.

There are a couple of solutions below which demonstrate some flexibility. You could do something like this:

<ui:param name="max" value="5"/>
<ui:repeat var="i" value="#{indexBean.values}" size="#{max}" >
 <tr><td>#{i}</td></tr>
</ui:repeat>

The maximum number of rows is determined by a a <ui:parameter> named max. This is not required, but does demonstrate flexibility. Alternatively you could use something like:

<ui:param name="max" value="5"/>
<ui:repeat var="i" value="#{indexBean.rowNumbers(max)}">
 <tr><td>#{i}</td></tr>
</ui:repeat>

The backing bean code is the following:

@ManagedBean
public class IndexBean {

public List<Integer> getValues() {
    List<Integer> values = new ArrayList<Integer>();
    for (int i = 0; i < 10; i++) {
        values.add(i);
    }
    return values;
}

public List<Integer> rowNumbers(final int max) {
    List<Integer> values = new ArrayList<Integer>();
    for (int i = 0; i < max; i++) {
        values.add(i);
    }
    return values;
}
}



回答2:


<c:forEach var="i" begin="1" end="#{someBean.max}">
             <td>#{i}</td>      
 </c:forEach>



回答3:


I suggest thinking at a higher level of abstraction, not in terms of rendering HTML tags, but in terms of using a component that does what you need. For example, Primefaces' datatable supports dynamic columns, which should be capable of replacing your on-page iteration logic.




回答4:


Simple example using ui repeat

<ul>
    <ui:repeat var="entry" value="${tourBean.tour.highlights}">
        <li class="pb-1">#{entry}</li>
    </ui:repeat>
</ul>



回答5:


with rich faces data table you can dynamically generate columns headers and values



来源:https://stackoverflow.com/questions/5258033/for-cycle-in-jsf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!