0

I have this bean in application scope.

public class User {
    private UICommand link;
    private String name;
    public User(){
        System.out.println("User.User()");
        name = "Test Link";
    }

    public UICommand getLink() {
        System.out.println("User.getLink()");
        System.out.println(link==null?"link is null":"link is not null");
        return link;
    }
    public void setLink(UICommand link) {
        System.out.println("User.setLink()");
        this.link = link;
        System.out.println("link: "+link.toString());
    }
    public void change(){
        System.out.println("User.change()");
    }
    //setter and getter for name
}

I have this jsf on jsp page.

<f:view>
<h:form>
<h:commandLink binding="#{user.link}" action="#{user.change}" value="#{user.name}"/>
</h:form>
</f:view>

I thought that the UICommand object would be reused (by sending the serialized state of the object along with the HTML output) and thus maintain the state and binding. But I get this sysoutput.

//When page loads
User.User()
User.getLink()
link is null
User.setLink()
link: javax.faces.component.html.HtmlCommandLink@14e4ce7

//when user clicks the link 
User.setLink()
link: javax.faces.component.html.HtmlCommandLink@6fcc9c
User.change()

UICommand object is different each time the user clicks the link!!! Also i believe getLink() runs only once when that object is first loaded on page but if that's the case then the page woudn't reflect the latest UICommand object!

John Eipe
  • 10,922
  • 24
  • 72
  • 114

1 Answers1

2

No, each time the component tree is built/restored, you get completely new instances of UICommand. But these instances restore their state from the JSF state saving mechanism.

But you shouldn't use bindings intensively. There is almost never a good reason to do so. If you do so, always use request scope for the bean, because you will run into problems otherwise.

chkal
  • 5,598
  • 21
  • 26
  • how does it maintain state if it create new instances of UICommand? – John Eipe Feb 23 '13 at 08:51
  • 1
    They implement an interface called StateHolder. The interface contains saveState() and restoreState() methods. See: http://docs.oracle.com/javaee/6/api/javax/faces/component/StateHolder.html – chkal Feb 23 '13 at 09:51