首页 > 解决方案 > 如何检测单击的按钮的名称并设置要评估的布尔变量?

问题描述

我有一个 actionListener 来检测何时单击命令按钮,然后我打算将一个布尔变量设置为 true 并在另一个要执行的方法中对其进行评估;如果为真,则加载一些项目;如果为假,则加载其他项目:

xhtml:

<h:form id="myFormID" ... >
    <p:commandButton id="myButtonID" value="Some Title" action="#{myController.pressedFilter()}" actionListener="#{myController.checkClicked}" />
...
</h:form>

控制器类:

//the boolean variable:
private boolean clicked;

public boolean isClicked() {
    return clicked;
}

public void setClicked(boolean clicked) {
    this.clicked = clicked;
}

//the actionListener to detect the button clicked:
public boolean checkClicked(ActionEvent ev) {
    String buttonClickedID = ev.getComponent().getClientId();

    if (buttonClickedID.equals("myFormID:myButtonID")) {
        setClicked(true);
    }

    return clicked;
}

//the method to retrieve the items:
public Collection<T> getItems() {
    if (isClicked()) {
        items = this.ejbFacade.findSomeItems();
    } else if (!isClicked()) {
        items = this.ejbFacade.findAnotherItems();
    } 
return items;
}

//clears all datatable filters:
public String pressedFilter() {
    clearAllFilters();
    return "/app/index";
}

不幸的是,我不知道为什么它没有像我预期的那样工作。

如果我单击命令按钮,则布尔变量设置为 true;但是在评估它时,我不知道为什么这个值是假的。

有人可以解释我做错了什么并帮助我修复它以使其按我描述的那样工作吗?

提前致谢。

标签: primefacesactionlisteneractionevent

解决方案


As mentionend in the comments. The problem is that you're using a @ViewScoped bean, which is recreated every time the view changes (e.g. browser refresh). Check it out: JSF Scopes.

So, changing your bean scope to @SessionScoped may solve the problem.


推荐阅读