开发者

NullpointerException Binding not working JSF managed bean

开发者 https://www.devze.com 2022-12-23 03:30 出处:网络
I created a simple HtmlInputText <h:inputText binding=\"#{IndexBean.objUIInput}\" /> Then in my managed bean, it is :-

I created a simple HtmlInputText

  <h:inputText binding="#{IndexBean.objUIInput}" />

Then in my managed bean, it is :-

   private   UIInput objUIInput;

    public UIInput getObjUIInput() {
        objUIInput.setValue("laala");
        return objUIInput;
    }

    pub开发者_如何学Golic void setObjUIInput(UIInput objUIInput) {
        System.out.println("Set!!");
        this.objUIInput = objUIInput;
    }

But i always get NullpointerException. Do i need to do anything extra on my JSF page? like we do jsp:usebean setproperty? Please help me.


Whenever you'd like to change the component's default state/behaviour prior to display, then you need to instantiate it yourself. I.e. during declaration:

private UIInput objUIInput = new HtmlInputText();

or during construction:

public Bean() {
    this.objUIInput = new HtmlInputText();
}

or, as Bozho suggested, using @PostConstruct:

@PostConstruct
public void init() {
    this.objUIInput = new HtmlInputText();
}

(which will take place after construction of the bean and initialization/setting of all managed properties).

And indeed, you should preferably not do any business logic in getters/setters. They are to be used to access bean properties and they can be called more than once during bean's life.

As per the comments, you can alternatively also move the UIInput#setValue() call to the setter method. JSF will call it once directly after precreating the component.

public void setObjUIInput(UIInput objUIInput) {
    this.objUIInput = objUIInput;
    this.objUIInput.setValue("laala");
}


When you bind a component, the getter and setter are supposed to be simple - only get/set - no logic inside them.

Perhaps the JSF lifecycle is calling the getter to check whether it needs to instantiate the component, and the getter initially would throw a NPE.

Remove all logic from your getter, or at least add a null check.

Actually, I'd advice for not using binding at all.

If you want to set an initial value to your component, use a method annotated with @PostConstruct and assign the value there, then use the value attribute.

0

精彩评论

暂无评论...
验证码 换一张
取 消