I\'m still new to SpringMVC (and jstl for that matter). I\'m trying to populate options in a select from a list of objects. I\'ve found a way to do it using c:forEach, but I k
Usualy I am doing it with spring tag like this :
<springform:select path="myObjectList" id="selected_company">
<springform:option value="0" label="--- Select One ---"></springform:option>
<springform:options items="${myObjectList}" itemValue="company" itemLabel="company"></springform:options>
</springform:select>
don't forget including the namespace declaration : xmlns:springform="http://www.springframework.org/tags/form"
The Spring Documentation says this about the items
attribute of the form:options
tag:
The items attribute is typically populated with a collection or array of item objects. itemValue and itemLabel simply refer to bean properties of those item objects, if specified; otherwise, the item objects themselves will be stringified. Alternatively, you may specify a Map of items, in which case the map keys are interpreted as option values and the map values correspond to option labels. If itemValue and/or itemLabel happen to be specified as well, the item value property will apply to the map key and the item label property will apply to the map value.
In a nutshell, if you need to use a List of your Custom Beans as the items attribute you need to use also the itemValue
and itemLabel
attributes. Personally, I'll prefer using Maps -LinkedHashMap
instances speciffically- for populating my select tags, but that's a matter of taste.
Adapting an example from the Spring Documentation, your code should look like this:
<form:select path="commandAttribute">
<form:option value="-" label="--Please Select"/>
<form:options items="${countryList}" itemValue="company" itemLabel="company"/>
</form:select>
I'm using the company
attribute as both itemValue
and itemLabel
, but you're free to choose the attributes that fit your requirements.