如何在我的托管bean中识别单击的commandButton

时间:2012-10-09 10:02:17

标签: jsf

我的托管bean中有一个actionListener方法,由许多命令按钮调用。

public void verifyTestDisponibility(ActionEvent actionEvent) {
    if (button1 clicked) {
        // ...
    }
    if (button2  clicked) {
        // ...
    }
}

我正在坚持的部分是识别点击的命令按钮。我如何识别它?

3 个答案:

答案 0 :(得分:7)

您可以像这样使用

在xhtml页面中,我们可以使用<h:commandButton>标记和actionListener

<h:commandButton id="btn1" action="#{yourBean.method}" value="ButtonValue"
   actionListener="#{yourBean.commandClicked}"></h:commandButton>

在托管bean中

private String buttonId;
/* getters and setters for buttonId goes here */

public void commandClicked(ActionEvent event) {
  /* retrieve buttonId which you clicked */
  buttonId = event.getComponent().getId();

  /*check for which button you clicked*/
  if(buttonId.equals("btn1")){

  }else{

  }
}

答案 1 :(得分:2)

您可以使用event.getComponent().getClientId();

if (event.getComponent().getClientId().equals("firstButton")).....

答案 2 :(得分:0)

这也适用于ajax监听器。我曾经使用过Primefaces 5 ajax监听器。例如:

public void myListener(AjaxBehaviorEvent ev) {
  String clientId = ev.getComponent().getClientId();
  ...
}