【问题标题】:How to pass parameter to a ViewScoped Bean如何将参数传递给 ViewScoped Bean
【发布时间】:2012-09-06 08:19:31
【问题描述】:

简要用例描述:

用户到达页面:http://localhost:8080/.../show.xhtml?itemId=1。 我的ShowBean 是一个@RequestScoped JSF Managed Bean,它通过<f:viewParam.../> 获取id 并在数据库中查找项目:

<f:metadata>
    <f:viewParam name="itemId" value="#{showBean.itemId}">
        <f:convertNumber integerOnly="#{true}"/>
    </f:viewParam>
</f:metadata>
<f:event type="preRenderView" listener="#{showBean.init()}"/>

用户还可以编辑显示的项目。我想按需构建@ViewScoped ItemEditBean(通过单击“编辑”按钮)。为此,我做了以下工作:

<p:commandButton value="Edit" oncomplete="editWidget.show()" update=":itemEditForm">
    <f:setPropertyActionListener target="#{itemEditBean.id}" value="#{showBean.itemId}"/>
</p:commandButton>

我的问题是:有没有更好的方法将 itemId 传递给 @ViewScoped bean?

编辑:

p:command 按钮的操作中执行itemEditBean.fetch(id) 不会在页面呈现时初始化@ViewScoped bean。

&lt;p:commandButton value="Edit" oncomplete="editWidget.show()" update=":itemEditForm" action="#{itemEditBean.fetchItem(showBean.itemId)}"/&gt;.

通过上面的代码,itemEditBean 可以按需构建。

【问题讨论】:

    标签: java jsf jsf-2


    【解决方案1】:

    我认为@ViewScoped 不是专业人士。 尝试部分表单提交。 比如像这样,

     <p:commandLink immediate="true" id="addAccessoriesLink" update=":accessoriesEntryForm">  
            <h:graphicImage url="/images/add.png" styleClass="action-img"/>
                  <f:setPropertyActionListener value="# AccessoriesActionBean.newAccessories}" target="#{AccessoriesActionBean.newAccessories}" />
      </p:commandLink>
    

    【讨论】:

      【解决方案2】:

      问题是showEditBean在后续请求中在INVOKE_APPLICATION上重新构造,不保留参数。

      只需确保使用f:param 保存它们。

      <p:commandButton value="Edit" oncomplete="editWidget.show()" update=":itemEditForm">
          <f:param name="itemId" value="#{showBean.itemId}"/>
          <f:setPropertyActionListener target="#{itemEditBean.id}" value="#{showBean.itemId}"/>
      </p:commandButton>
      

      附:您对 @ViewScoped bean 生命周期的看法是正确的:如果仅出现在 actions 中,它不是在页面加载时构建的!

      【讨论】:

      • 是的,我的对话是 dynamic="true" 所以你的假设是错误的。例如,如果您执行任何调用 @ViewScoped bean 中的方法返回空字符串的操作,则 @ViewScoped bean 将被销毁。因此,我既可以按需构建它,也可以通过 p:dialog 中的操作将其销毁。
      • 你有一些绑定="#{something}" 吗?你怎么知道你的豆子已经被破坏了?这仅适用于 。如果视图相同,则 bean 不会被销毁,除非绑定错误
      • 不,我没有任何绑定。如果用户单击对话框中的任何按钮,我将从我的@ViewScoped bean 返回 itemId=1。所以基本上是的,我有
      • 最后我做了类似&lt;p:commandButton value="Edit" oncomplete="editWidget.show()" update=":itemEditForm" action="#{itemEditBean.fetchItem(showBean.itemId)}"/&gt; 之类的事情,基本上就是我想要的。 itemEditBean 是按需构造的,显示的Bean 被填充并且 id 被传递。
      • static (在动态组件之外)ValueExpression 中具有 #{itemEditBean} 意味着 itemEditBean 是在页面加载时构建的,而不是按需构建的...考虑使用调试器或在构造函数/@PostConstruct 中打印出一条消息...确实可行,但仅使用一个 @ViewScoped bean 也是一样的...
      猜你喜欢
      • 2011-06-02
      • 2013-06-13
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 2014-05-24
      • 1970-01-01
      相关资源
      最近更新 更多