Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to do multiple actions on different managed beans with the same button, one being scoped session and the other request. In my example I use the same bean for both.

index.xhtml

    <h:form>
        <p:commandButton image="ui-icon ui-icon-notice" action="#{controller.inc()}" update="result">
            <f:actionListener type="controller.Controller" />
        </p:commandButton>
    </h:form>

    <p:panel id="result">
        #{controller.count}
    </p:panel>

controller.Controller.java

@Named(value = "controller")
@SessionScoped
public class Controller implements ActionListener, Serializable
{
    int count = 0;

    public Controller(){
        System.out.println("new");
    }

    public void inc(){
        count += 1;
    }

    public int getCount(){
        return count;
    }

    @Override
    public void processAction(ActionEvent event) throws AbortProcessingException{
        count += 1000;
    }
}

When I press the button the count increases by 1, instead of 1001, and creates a new bean. What did I do wrong ?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

That's expected behaviour. The <f:actionListener type> creates and gets its own bean instance on every declaration. It does not reuse the same session scoped bean which is managed by JSF.

You need to use binding instead to bind to the already-created session scoped bean instance.

<f:actionListener binding="#{controller}" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...