What is the correct way to bind input value to JSF managed bean property?
Asked Answered
T

3

5

I am new to JSF and managed beans. I have a managed bean with some private property with public setter and Getter methods. Now when I add the managed bean's properties to JSF forms, should I add the private methods directly or should I use call the property by Getter methods?

For example:

  1. <h:inputText value="#{BeanName.userName}"/>
  2. <h:inputText value="#{BeanName.getUserName()}"/>

Which one is correct in above?

Trubow answered 24/6, 2010 at 18:9 Comment(0)
V
6

Assuming that you're using JBoss EL or EL 2.2+, both ways would work fine in the initial display. But the first one is actually more correct because the second one would only get the value, but never set the value. If you want to collect input values, you should always go for the first way. The EL (Expression Language) will then automatically locate the getUserName() and setUserName() methods whenever needed.

The second way will never work when you're using standard JSF EL implementation since it doesn't support direct method calls.

To learn more about JSF, start at our JSF wiki page.

Vicentevicepresident answered 24/6, 2010 at 18:16 Comment(1)
Thank you guys. Both helped me to understand better.Trubow
K
1

If in your java class you have something like

....
private String coolStuff;

public String getCoolStuff() {
    return coolStuff;
}
....

Then in your jsf page you access it like so:

#{myBackingBean.coolStuff}

The framework automatically looks for a method called getCoolStuff()

Hope that helps

Keister answered 24/6, 2010 at 18:13 Comment(0)
T
0

number 1 is correct from above it is the private field that you connect if you are using EL with JSF in your form.

You still need the getter and the setter which the managed bean calls to get the values so you can save them in a database ....etc

Transpacific answered 25/6, 2010 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.