使用h:commandButton传递参数 - 或等效参数

时间:2011-09-09 19:22:49

标签: jsf-2

我在其他主题上读到这不起作用:

<h:commandButton value="Create New Account" 
                action="#{acctBean.doCreate}" >
   <f:param name="acctName" value="#{acctBean.handle}" />
   <f:param name="acctNo" value="#{acctBean.id}" />
</h:commandButton>

doCreate()方法会在创建帐户时将导航返回到“祝贺”页面。然后,目标网页可以解析#{param.handle}#{param.id}

我知道如果我改用h:commandLink,这会有效,但我想要一个按钮,而不是一个链接。是否有任何普遍接受的方式?

更新:

基于@BalusC的第一个答案,我创建了以下测试代码:

<h:commandButton value="Push Me" action="goAcctCreated" >
    <f:param name="acctName" value="This Is Account Name" />
    <f:param name="acctNo" value="1234" />
</h:commandButton>
<h:button value="Push Me #2" outcome="newAcct" >
    <f:param name="acctName" value="This Is Account Name" />
    <f:param name="acctNo" value="1234" />
</h:button>

在目标页面中我有:

<p>You may now log in with the account you just created: <b>#{param['acctName']}</b>.</p>
<p>This is account number <b>#{param['acctNo']}</b>.</p>

和以前一样,h:commandButton不适用于POST事务,正如BalusC所说,h:button执行GET并且确实有效。

有趣的是,在POST h:commandbutton上,它有编码的参数,如Firebug所见:

acctName    This Is Account Name
acctNo  1234
javax.faces.ViewState   8642267042811824055:-4937858692781722161
testForm    testForm
testForm:j_idt55    testForm:j_idt55

因此f:param标签至少在执行其工作,但目标页面无法解析EL表达式#{param[xxx]}。它们也不会出现在范围变量报告中(ctrl-shift-D)。我应该在目标页面上做些什么吗?

1 个答案:

答案 0 :(得分:6)

这应该在JSF 2.x上完全正常。你有没有亲自尝试过?如果它不起作用,那么你要么实际使用JSF 1.x,要么你在POST后发送重定向。

<f:param>确实不支持<h:commandButton>时,你所指的其他主题无疑是在谈论JSF 1.x.在JSF 1.x上,您可以使用<f:setPropertyActionListener>代替或使用一些CSS来将<h:commandLink>设置为按钮。

E.g。

<h:commandLink styleClass="button" ...>

a.button {
    display: inline-block;
    background: lightgray;
    border: 1px outset lightgray;
    outline: none;
    color: black;
    text-decoration: none;
    cursor: default;
}
a.button:active {
    border-style: inset;
}

请注意,在JSF 2.x中,您还有机会使用新的<h:button>来激发GET请求而不是POST请求。如果您不需要执行任何bean操作(即您当前的操作只返回一个简单的导航案例结果)并希望请求是幂等的,那么这样做会更好。

<h:button value="Create New Account" outcome="create">
    <f:param name="acctName" value="#{acctBean.handle}" />
    <f:param name="acctNo" value="#{acctBean.id}" />
</h:button>

这将使用请求网址中的给定参数导航到create.xhtml