无法得到

时间:2014-04-24 16:37:44

标签: java jsf

我在使用tUsers的名称并在屏幕上打印它时遇到问题。可能是我没有调用正确获取名称的方法(),因为当我调用函数listAgencies时,它会在Eclipse控制台中正确打印它们。感谢您的任何建议!

在.xthml文件中,我有:

<h:panelGrid id="panel2" columns="2" cellpadding="5">
            <c:forEach items="${agencyBean.listAgencies()}" var="inputBoxes">
                <h:outputText value="${inputBoxes.gettUser().name}" />
                <h:inputText />
            </c:forEach>
        </h:panelGrid>

我的豆类:

@ManagedBean(name = "agencyBean")
@SessionScoped
public class AgencyBean {

    private TAgency tEventType = new TAgency();

    public void listAgencies() {
        EntityManager em = HibernateUtil.getEntityManager();
        // read the existing entries and write to console
        Query q = em.createQuery("select u from TAgency u");
        List<TAgency> agencyList = q.getResultList();
        for (TAgency agency : agencyList) {
            System.out.println("NAme: " + agency.gettUser().getName());

        }
    }

    public TAgency gettEventType() {
        return tEventType;
    }

    public void settEventType(TAgency tEventType) {
        this.tEventType = tEventType;
    }
}

TUser是我想要获取名称的另一个实体。我有getName()方法是公共的。

1 个答案:

答案 0 :(得分:1)

问题在于:

<c:forEach items="${agencyBean.listAgencies()}" ... >

它应该为listAgencies属性寻找一个getter方法,但它是一个void方法,它将被执行并且无法访问。

最好的选择是:

  • 在您的班级中创建名为List<TAgency> listAgencies
  • 的属性
  • listAgencies属性定义正确的getter和setter方法。 从不在托管bean getter中定义业务逻辑。相关:Why JSF calls getters multiple times
  • 每次用户访问此视图时,可能会将bean的范围更改为@RequestScope以加载此列表。相关:How to choose the right bean scope?
  • 使用@PostConstruct方法加载列表。

基于这些建议,代码如下所示:

@ManagedBean(name = "agencyBean")
@RequestScoped
public class AgencyBean {

    private TAgency tEventType = new TAgency();
    private List<TAgency> listAgencies;

    @PostConstruct
    public void init() {
        EntityManager em = HibernateUtil.getEntityManager();
        // read the existing entries and write to console
        Query q = em.createQuery("select u from TAgency u");
        List<TAgency> agencyList = q.getResultList();
        for (TAgency agency : agencyList) {
            System.out.println("NAme: " + agency.gettUser().getName());
        }
    }

    public TAgency gettEventType() {
        return tEventType;
    }

    public void settEventType(TAgency tEventType) {
        this.tEventType = tEventType;
    }

    public List<TAgency> getListAgencies() {
        return listAgencies;
    }

    public void setListAgencies(List<TAgency> listAgencies) {
        this.listAgencies = listAgencies;
    }
}

你的JSF代码:

<!-- Note: no parenthesis usage -->
<c:forEach items="#{agencyBean.listAgencies}" var="inputBoxes">
    <!-- no need to call the getter verbosely, Expression Language call it for you automatically -->
    <h:outputText value="#{inputBoxes.user.name}" />
    <!-- what you want to do here? -->
    <h:inputText />
</c:forEach>

此外,您可能不想使用<c:forEach>而是使用<ui:repeat>。相关:JSTL in JSF2 Facelets... makes sense?