Backing bean in composite component is recreated on every request

后端 未结 2 1558
南笙
南笙 2020-12-16 07:22

I have two variables \"userId\" and \"name\". When I click for example the \"SHOW USERID\" button it works fine and sets \"renderUserId=true\" and it shows it with the \"ren

相关标签:
2条回答
  • 2020-12-16 07:54

    Your FacesComponent does not keep a state, it's a new instance everytime you call it. For your use case it seems you should use a ManagedBean with a view scope at least. This means that as long as you're on the page with the buttons, the instance is kept.

    0 讨论(0)
  • 2020-12-16 08:04

    There's a major misconception going here. That's not a backing bean. That's a backing component.

    JSF UI component instances are not view scoped, instead they are request scoped. They are destroyed by end of render response (after having saved their state into JSF view state) and recreated during view build time (and their state is restored from JSF view state).

    You've assigned the stateful properties as instance variables of the component. This is not right. You should be explicitly storing them in the JSF state. The correct approach for that is to let the getter and setter delegate to UIComponent#getStateHelper(). Any attributes which are declared as <cc:attribute> already implicitly do that. You do absolutely not need to redeclare them as instance variables of the backing component.

    Those booleans which are not declared as <cc:attribute> must be reimplemented like follows:

    public Boolean getRenderUserId() {
        return (Boolean) getStateHelper().eval("renderUserId", Boolean.FALSE);
    }
    
    public void setRenderUserId(Boolean renderUserId) {
        getStateHelper().put("renderUserId", renderUserId);
    }
    

    In your action(listener) method, just invoke setRenderUserId(true) accordingly.

    Don't forget to fix the EL expressions accordingly:

    #{cc.renderUserId} 
    

    See also:

    • JSF composite component - weird behavior when trying to save state
    • Our composite component wiki page
    • Composite component with multiple input fields
    0 讨论(0)
提交回复
热议问题