【问题标题】:How can I transport an entity from one jsf-view to another?如何将实体从一个 jsf 视图传输到另一个?
【发布时间】:2012-11-08 10:55:28
【问题描述】:

我有以下结构:

listView.xhtml

<h:dataTable value="#{listBean.myList} ...>
  //for every row I create a commandLink
  <h:commandLink action="editView" value="edit" />
</h:dataTable>

ListBean.java

@ManagedBean
@ViewScoped
public class ListBean{
   public List<Entity> myList; // also getters and setters
}

editView.xhtml

<h:inputText value="#{editBean.selectedEntity.name}" />

EditBean.java

@ManagedBean
@ViewScoped
public class EditBean{
   public Entity selectedEntity; // also getters and setters
}

您知道问题:如何将选定的实体从 listView 传输到 editView?我想这应该很简单,但是一整天后,我没有成功。

我尝试了不同的东西,例如 @ManagedProperty 和 &lt;f:param name="" value=""&gt;,但我没有帮助。 所以,请告诉我这有多简单和好:)

提前致谢!


更新 - 解决方案#1

感谢丹尼尔, 一种可行的方法是,当实体由 EntityManager 持有时,您可以通过其 id 访问实体。因此,您将 id 作为请求参数传递。我们开始:

listView.xhtml

<h:dataTable value="#{listBean.myList} ...>
  //for every row I create a commandLink, so you can click on that entity to edit it
  <h:commandLink action="editView" value="edit">
     <f:param name="selectedEntityId" value="#{entity.id}" />
  </h:commandLink>
</h:dataTable>

EditBean.java

@ManagedBean
@ViewScoped
public class EditBean{

    private Entity selectedEntity;

    @PostConstruct
    public void init() {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        long selectedEntityId = Long.parseLong(params.get("selectedEntityId"));

        selectedEntity = SomeEntityManagerUtil.getEntity(selectedEntityId);
    }
}

【问题讨论】:

  • &lt;f:param 没有key 属性,它被称为name
  • ups,我纠正了帖子中的错误。但问题是 RequestParameterMap.get("paramName") 只返回字符串而不是实体对象。
  • 比传递 id 并通过 id 获得一个 entity ,或者使用 converter 并在其中将 id 转换为实体...
  • 这行得通!谢谢。我将更新我的问题以提供解决方案。但尽管如此,我认为有一个更简单的解决方案;)

标签: java jsf views managed-bean scopes


【解决方案1】:

一般的想法可能是:

传递该实体的 id 并稍后通过该 ID 获取实体...

您也可以使用转换器并在其中翻译该 id 为实体...

像这样:

<h:inputText value="#{editBean.selectedEntity.name}" converter="myEntityConverter"/>

【讨论】:

    【解决方案2】:

    如果它们具有相同的范围,也许你应该合并你的bean? 您还可以使用上下文: jsf-get-managed-bean-by-name

    也看这个问题: passing-data-between-managed-components-in-jsf

    【讨论】:

    • 我认为如果从 listView 导航到 editView,视图已经改变,因此 @ViewScoped Beans 被清除(这是正确的吗?)。没有办法通过 RequestScope 发送 Beans 吗?因为这只是一个请求……还是不是?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多