電卓を表す Bean クラスがあります。このクラスは、加算、減算、乗算、および除算の 4 つのメソッドを公開します。
フロント エンドでは、JSP ページを作成しています。このページには 2 つのテキスト入力ボックス (x 用と y 用) があります。ユーザーが操作を選択するプルダウン メニューと、選択した操作を実行する 1 つの[計算] コマンド ボタンがあります。
<h:form>
<h:inputText value="#{calcBean.x}"></h:inputText>
<h:inputText value="#{calcBean.y}"></h:inputText>
<h:selectOneMenu>
<f:selectItem itemValue="Add"></f:selectItem>
<f:selectItem itemValue="Subtract"></f:selectItem>
<f:selectItem itemValue="Multiply"></f:selectItem>
<f:selectItem itemValue="Divide"></f:selectItem>
</h:selectOneMenu>
<h:commandButton value="Calculate" action="@SEE COMMENT">
<%-- TODO the action of this command button needs to change depending on --%>
<%-- the user selection. For example: If the user selects "Add" the action --%>
<%-- needs to be #{calcBean.add} --%>
</h:commandButton>
</h:form>
私が直面している問題は、ユーザーの選択に応じてコマンド ボタンのアクションを変更する方法がわからないことです。
4 つの異なるコマンド ボタンを使用してこれを行うこともできますが、それは洗練された解決策ではありません。
<h:form>
<h:inputText value="#{calcBean.x}"></h:inputText>
<h:inputText value="#{calcBean.y}"></h:inputText>
<br/>
<h:commandButton value="Add" action="#{calcBean.add}"></h:commandButton>
<h:commandButton value="Subtract" action="#{calcBean.subtract}"></h:commandButton>
<h:commandButton value="Multiply" action="#{calcBean.multiply}"></h:commandButton>
<h:commandButton value="Divide" action="#{calcBean.divide}"></h:commandButton>
</h:form>