Pages

2014-06-13

Java EE (JSF): Initializing List and Array properties for Managed Beans

If you have a property that is an array or a List, you can initialize it with default values. If the property is set to null, the facility will create a new List or array and initialize it for you. If it’s non-null, the facility will simply add any values you define to the existing collection.

Instead of specifying a single value for the property, you specify multiple values. You can configure a List or array property by nesting <value> or <null-value> elements inside a <list-entries> element, which is a child of the <managed-property> element.

Let’s say our UserBean class also has a favoriteSites property, which is a List of Strings representing the user’s favorite sites. If we wanted to provide a default list of values for the favoriteSites property, we could define it like so:

<managed-bean><managed-bean-name>user</managed-bean-name><managed-bean-class>org.jia.examples.UserBean</managed-bean-class><managed-bean-scope>request</managed-bean-scope>...<managed-property><property-name>favoriteSites</property-name><list-entries><value>http://www.jsfcentral.com</value><value>http://www.theserverside.com</value><value>http://www.ibm.com/developerworks/</value><value>http://otn.oracle.com</value><value>http://www.java.net</value><value>http://www.manning.com</value></list-entries></managed-property>...</managed-bean>

In the previous example, all values were stored as String objects, which is the default. If you want all of the values to be converted to a specific type, you can use the <value-class> attribute. Here’s a List property whose values are all Integers:

<managed-bean>...<managed-property><property-name>favoriteNumbers</property-name><list-entries><value-class>java.lang.Integer</value-class><value>31415</value><value>278</value><value>304</value><value>18</value><value>811</value><value>914</value></list-entries></managed-property>...</managed-bean>

No comments:

Post a Comment