我正在尝试创建一个按钮,单击该按钮将更改bean中的属性。
<h:commandButton type="button" action="#{loginBean.withdraw}" id="thousand" class="buttons" style="top:180px;left:570px;">
<f:setPropertyActionListener target="#{loginBean.withdrawAmount}" value="1000" />
</h:commandButton>
public class LoginBean {
int withdrawAmount;
此方法仅在我省略type="button"
中的commandButton
时才有效,但type="button"
它不起作用,我不确定原因。
我需要type="button"
在那里,是否有任何方法可以保留它并仍能使其正常工作?
答案 0 :(得分:2)
您的facelet代码段中存在错误:
class
的没有属性<h:commandButton>
。可能你的意思是styleClass
。至于你遇到的问题,你必须:
为withdrawAmount
属性提供了一个setter方法
public void setWithdrawAmount(int withdrawAmount) {
this.withdrawAmount = withdrawAmount;
}
并且您的facelet应如下所示:
<h:commandButton type="submit"
action="#{loginBean.withdraw}"
id="thousand"
styleClass="buttons"
style="top:180px;left:570px;">
<f:setPropertyActionListener target="#{loginBean.withdrawAmount}"
value="1000" />
</h:commandButton>
或 ,您可以摆脱<f:setPropertyActionListener>
并添加一条声明,将withdrawAmount
的值更改为第一行#{loginBean.withdraw}
方法。
在这种情况下,您的facelet代码段应如下所示:
<h:commandButton type="submit"
action="#{loginBean.withdraw}"
id="thousand"
styleClass="buttons"
style="top:180px;left:570px;" />
并且您的LoginBean#withdraw()
方法应该以更改withdrawAmount
值的语句开头:
public String withdraw() {
this.withdrawAmount = 1000;
//the remaining logic.
}
就个人而言,我更喜欢第一种选择。
更多信息:
答案 1 :(得分:2)
type
是您遇到此问题的全部原因。我发布了这个答案,因为接受的答案并没有解释为什么你遇到了这个问题。
<h:commandButton/>
旨在以3种模式运作:
submit
:这是按钮设置的默认模式。此模式向触发JSF请求处理生命周期的服务器发送HTTP POST请求。只有这种模式才能触发支持bean方法(使用action
或actionListener
属性)。
button
:此模式在应用程序中触发GET请求。随着GET请求的进行,该模式主要适用于导航,即请求另一个视图或页面。在这种模式下,没有简单/直接的方法来执行支持bean代码,或触发JSF请求处理生命周期。这是您目前的问题
reset
:此模式只是重置其封闭的<h:form/>
参考: