2010-06-16 125 views
1

我对JSF(v2.0)非常陌生,我试图在netbeans.org和coreservlets.com等地方学习它。我正在研究一个非常简单的“加/减/乘/除”Java Web应用程序,我遇到了一个问题。当我第一次开始时,应用程序输入两个数字,并按'+'键,它们会自动添加在一起。现在我增加了更多的复杂性,因此无法对托管bean执行操作。这就是我已经当它只是“添加”:Glassfish抱怨JSF组件ID

<h:inputText styleClass="display" id="number01" size="4" maxlength="3" value="#{Calculator.number01}" /> 
<h:inputText styleClass="display" id="number02" size="4" maxlength="3" value="#{Calculator.number02}" /> 
<h:commandButton id="add" action="answer" value="+" /> 

对于“答案”页面上,我显示这样的答案:

<h:outputText value="#{Calculator.answer}" /> 

我有适当的getter和setter的Calculator.java托管bean,操作完美。

现在我已经添加了其他三个操作,而且我很难想象如何将操作参数传递给bean,以便我可以切换它。我试过这个:

<h:commandButton id="operation" action="answer" value="+" />  
<h:commandButton id="operation" action="answer" value="-" /> 
<h:commandButton id="operation" action="answer" value="*" /> 
<h:commandButton id="operation" action="answer" value="/" /> 

然而,Glassfish抱怨说我已经使用过“手术”一次,而我正试图在这里使用它四次。

任何有关如何获取托管bean的多个操作的Adivce /技巧,以便它可以执行预期的操作?

感谢您花时间阅读。

回答

2

组件id确实应该是唯一的。这是HTML规范隐含要求的。你知道,所有的JSF都只是生成适当的HTML/CSS/JS代码。给他们所有不同的id或者只是把它留下,它在这种特定的情况下没有额外的价值(除非你想钩上一些CSS/JS)。

要达到您的功能要求,您可能会发现f:setPropertyActionListener有用。

<h:commandButton action="answer" value="+"> 
    <f:setPropertyActionListener target="#{calculator.operation}" value="+" /> 
</h:commandButton>  
<h:commandButton action="answer" value="-"> 
    <f:setPropertyActionListener target="#{calculator.operation}" value="-" /> 
</h:commandButton>  
<h:commandButton action="answer" value="*"> 
    <f:setPropertyActionListener target="#{calculator.operation}" value="*" /> 
</h:commandButton>  
<h:commandButton action="answer" value="/"> 
    <f:setPropertyActionListener target="#{calculator.operation}" value="/" /> 
</h:commandButton>  

而且有一个属性operationcalculator托管bean:

private String operation; // +setter. 

您可以访问它在getAnswer()方法和相应的处理。


或者,让这些按钮的每个点提供不同的bean行动,但返回所有"answer"

<h:commandButton action="#{calculator.add}" value="+" />  
<h:commandButton action="#{calculator.substract}" value="-" />  
<h:commandButton action="#{calculator.multiply}" value="*" />  
<h:commandButton action="#{calculator.divide}" value="/" />  

与您calculator托管bean以下方法:

public String add() { 
    answer = number1 + number2; 
    return "answer"; 
} 

public String substract() { 
    answer = number1 - number2; 
    return "answer"; 
} 

// etc... 

和只要让getAnswer()返回answer并在那里别的什么都不做。这是一个更清晰的职责分离。

+1

_组件ID确实应该是unique._ - 对NamingContainer来说是唯一的,但这可能不是初学者想要探讨的主题。 – McDowell 2010-06-16 16:08:31

+0

@McDowell:我已经犹豫了,以添加此信息,但我决定保持这个细节:) – BalusC 2010-06-16 16:11:00

+0

BalusC - 完美的工作!谢谢。 – Brian 2010-06-16 16:24:47