How do I display a list of items from a Bean onto a JSF webpage?
JSF2 offers two iterating components out the box: <ui:repeat>
and <h:dataTable>
. The former renders nothing to the response (so you have 100% control over the final HTML output), while the latter renders a HTML <table>
to the response and requires a <h:column>
to represent a column of <td>
s. Both components can take among others a List<E>
as value.
So, you can just have your managed bean like follows:
@ManagedBean
@RequestScoped
public class BookCatalog implements Serializable {
private List<Book> books;
@PostConstruct
public void init() {
books = new ArrayList<Book>();
books.add(new Book(1, "Theory of Money and Credit", "Ludwig von Mises"));
books.add(new Book(2, "Man, Economy and State", "Murry Rothbard"));
books.add(new Book(3, "Real Time Relationships", "Stefan Molyneux"));
}
public List<Book> getBooks() {
return books;
}
}
And you can use <ui:repeat>
to generate for example an <ul><li>
:
<ul>
<ui:repeat value="#{bookCatalog.books}" var="book">
<li>
<h:link value="#{book.title}" outcome="book">
<f:param name="id" value="#{book.id}" />
</h:link>
</li>
</ui:repeat>
</ul>
(note that the var
attribute basically exposes the currently iterated item by exactly the given name in the EL scope within the component)
And here's how to use a <h:dataTable>
instead:
<h:dataTable value="#{bookCatalog.books}" var="book">
<h:column>
<h:link value="#{book.title}" outcome="book">
<f:param name="id" value="#{book.id}" />
</h:link>
</h:column>
</h:dataTable>
As to the JSTL <c:forEach>
, that's also quite possible, but you should keep in mind that JSTL tags have a different lifecycle than JSF components. Long story short: JSTL in JSF2 Facelets... makes sense?
See also:
- How to choose the right bean scope?
- How and when should I load the model from database for h:dataTable
- Creating master-detail pages for entities, how to link them and which bean scope to choose
You can also use PrimeFaces library
Link: PrimeFaces datatable