2

我有一个带有数据表的页面。我希望表格中的某些项目链接到相应的视图页面。

例如,现在我有一个没有链接的表:

<h:dataTable var="bean" value="#{beanServiceImpl.beans}" border="1">
    <h:column>#{bean.id}</h:column>
  </h:dataTable>

我想为一些条目添加超链接,并让它们转到一个查看页面,根据它们的 id 显示更多信息:

  <h:dataTable var="bean" value="#{beanServiceImpl.beans}" border="1">
    <h:column>
        <a href="viewBean.xhtml?id=#{bean.id}">#{bean.id}</a>
    </h:column>
  </h:dataTable>

ViewBean.xhtml 将包含如下内容:

ViewBean.xhtml

<ul>
  <li>ID: #{bean.id}</li>
  <li>Field 1: #{bean.field1}</li>
  <li>Field 2: #{bean.field2}</li>
</ul>

我如何在 JSF 中完成这样的事情?我知道我必须编写一个控制器来查询其他字段的 id。但是如何让 viewBean.xhtml 运行业务逻辑来获取其他字段并呈现它呢?

4

3 回答 3

6

BalusC 的答案几乎很好,但不起作用(编辑:它现在起作用了)。

您已经知道如何将值添加到参数中。顺便说一句,如果我是你,我不会使用<a href>,而是:

<h:link outcome='viewBean'>
    <f:param name='id' value='#{bean.id}' />
</h:link>

现在,在获取价值时,您必须做出选择。最简单的方法是在 id 属性上方添加注释:

@ManagedProperty("#{param.id}") // this will inject id from param into id
private Long id;


//  (getters and setters are obligatory)


@PostConstruct // this will execute init() after id is injected
public void init() {

}

最后一件事:拥有一个名为“bean”的变量与称其为“变量”(或拥有一只名为 Dog 的狗和名为 Cat 的猫)没有任何意义。它不携带任何信息,更糟糕的是,它使您的应用程序中的所有 bean 都无法区分(除非您构建了一个豆类管理器)。

于 2011-02-02T09:53:53.903 回答
3

我假设 JSF 2.x。将此添加到您的Bean

@ManagedProperty(value="#{param.id}")
private Long id;

(这基本上是bean.setId(request.getParameter("id"))在视图加载时执行的)

它将@PostConstructBean.

@PostConstruct
public void init() {
    // Fill model based on id.
}
于 2011-02-02T00:52:04.843 回答
2

这就是我所做的。

    <h:form>
        <h:commandLink action="#{bean.populateBean}" value="#{bean.id}">
            <f:setPropertyActionListener target="#{bean.id}" value="#{bean.id}" />
        </h:commandLink>
    </h:form>

在我的 Bean.java 类中,我添加了动作控制器:

public String populateBean(){
    Bean bean = BeanServiceImpl.getBean(id); //id was injected by the commandLink
    this.field1 = tenure.getField1();
    this.field2 = tenure.getField2();

    return("viewBean");
}

我的 ViewBean.xhtml 是一样的:

<ul>
  <li>ID: #{bean.id}</li>
  <li>Field 1: #{bean.field1}</li>
  <li>Field 2: #{bean.field2}</li>
</ul>
于 2011-02-02T17:15:42.260 回答