代码之家  ›  专栏  ›  技术社区  ›  Brian

Glassfish抱怨JSF组件ID

jsf
  •  1
  • Brian  · 技术社区  · 16 年前

    我对JSF(v2.0)非常陌生,我正试图在netbeans.org和coreservlets.com等网站上学习它。我正在研究一个非常简单的“加/减/乘/除”Java WebApp,我遇到了一个问题。当我刚开始的时候,应用程序输入了两个数字,点击一个“+”键,它们将自动添加到一起。现在,我增加了更多的复杂性,我很难将操作传递到托管bean。这就是我在“添加”时所拥有的:

    <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}" />  
    

    我在calculator.java管理bean中有适当的getter和setter,并且操作非常成功。

    现在我已经添加了其他三个操作,并且我很难想象如何将操作参数获取到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/tips?

    感谢您抽出时间阅读。

    1 回复  |  直到 16 年前
        1
  •  2
  •   BalusC    16 年前

    组成部分 id 应该是独一无二的。这是HTML规范隐式要求的。你知道,JSF所做的只是生成适当的HTML/CSS/JS代码。给他们一个不同的 身份证件 或者只是把它放在一边,它在这种特定的情况下没有额外的价值(除非你想在它上面挂一些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>      
    

    拥有财产 operation 在你 calculator 管理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="/" />      
    

    在您的 计算器 管理bean:

    public String add() {
        answer = number1 + number2;
        return "answer";
    }
    
    public String substract() {
        answer = number1 - number2;
        return "answer";
    }
    
    // etc...
    

    就让 获得应答() 返回 answer 在那里什么也不做。这是更明确的职责分离。

    推荐文章