2010-06-16 126 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