本文介绍了如何遍历List< T>并在JSF Facelets中渲染每个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想知道如何在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:

  1. ,这是一个生成HTML <table>的UI组件.

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

  • ,它是在视图构建时而不是视图渲染时运行的标记处理程序(此处的背景说明:),它也不会产生任何HTML标记:

  • <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>
    

  • 另请参见:

    09-07 01:33