问题描述
我想知道如何在Facelet中显示如下所示的List<T>
:
I am wondering how to display a List<T>
as obtained below in a Facelet:
public List<T> searchByString(String string) {
return getEntityManager().createNamedQuery("Userdetails.findByUsername").setParameter("username", "%" + string + "%").getResultList();
}
<h:dataTable>
是合适的方法吗?
推荐答案
您将需要对其进行迭代. JSF 2提供了三个迭代组件.前提是User
实体如下所示,
You're going need to iterate over it. JSF 2 offers three iteration components out the box. Provided that the User
entity look like below,
@Entity
public class User {
private @Id Long id;
private String username;
private String email;
private LocalDate birthdate;
// Add/generate getters+setters.
}
,并且将搜索结果分配为Bean的List<User> users
属性,该属性可以作为#{bean}
,
and that the search results are assigned as a List<User> users
property of a bean which is available as #{bean}
,
@Named @RequestScoped
public class Bean {
private List<User> users;
// Add/generate postconstruct+getter.
}
以下是一些基于此的示例:
here are some examples based on it:
<h:dataTable>
, an UI component which generates a HTML<table>
.
<h:dataTable value="#{bean.users}" var="user">
<h:column>#{user.id}</h:column>
<h:column>#{user.username}</h:column>
<h:column><a href="mailto:#{user.email}">#{user.email}</a></h:column>
<h:column>#{user.birthdate}</h:column>
</h:dataTable>
,它是一个不会生成HTML标记的UI组件(因此,您必须自己以所需的方式编写所有HTML,可以轻松将其更改为例如<ul><li>
,<dl><dt><dd>
或<div><span>
等):
<ui:repeat>
, an UI component which generates no HTML markup (so, you'd have to write all that HTML in the desired fashion yourself, which could easily be changed to e.g. <ul><li>
, or <dl><dt><dd>
, or <div><span>
, etc):
<table>
<ui:repeat value="#{bean.users}" var="user">
<tr>
<td>#{user.id}</td>
<td>#{user.username}</td>
<td><a href="mailto:#{user.email}">#{user.email}</a></td>
<td>#{user.birthdate}</td>
</td>
</ui:repeat>
</table>
<c:forEach>
, a tag handler which runs during view build time instead of view render time (background explanation here: JSTL in JSF2 Facelets... makes sense?), it also doesn't produce any HTML markup:
<table>
<c:forEach items="#{bean.users}" var="user">
<tr>
<td>#{user.id}</td>
<td>#{user.username}</td>
<td><a href="mailto:#{user.email}">#{user.email}</a></td>
<td>#{user.birthdate}</td>
</td>
</c:forEach>
</table>
另请参见:
- Java EE 6教程-向页面添加组件-使用
<h:dataTable>
- >如何以及何时从中加载模型h:dataTable的数据库
- Java EE 6 tutorial - Adding components to a page - using
<h:dataTable>
- How and when should I load the model from database for h:dataTable
See also:
这篇关于如何遍历List< T>并在JSF Facelets中渲染每个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!