Can someone please tell me what do I need to specify in <form:select>
path attribute and what it's used for? actually I need to understand how the value of the selected item from the dropdown is passed onto the controller?
问题:
回答1:
Say you have a model (Dog for example), a Dog
has various attributes:
name
age
breed
if you want to make a simple form for adding/editing a dog, you'd use something that looks like this:
<form:form action="/saveDog" modelAttribute="myDog">
<form:input path="name"></form:input>
<form:input path="age"></form:input>
<form:select path="breed">
<form:options items="${allBreeds}" itemValue="breedId" itemLabel="breedName" />
</form:select>
</form:form>
As you can see, I've chosen the breed
property to be a select
, because I don't want the user to type whatever breed he want, I want him to choose from a list (allBreeds
in this case, which the controller will pass to the view).
In the <form:select>
I've used path
to tell spring that the select has to bind to the breed
of the Dog
model.
I've also used <form:options>
to fill the select with all the options available for the breed
attribute.
The <form:select>
is smart, and if it's working on a populated model (i.e a Dog
fetched from the database or with default breed value) - it will automatically select the "right" option from the list.
In this case, the controller will look similar to this:
@RequestMapping(value="/saveDog")
public String saveDog(@ModelAttribute("myDog") Dog dogFromForm){
//dogFromForm.getBreed() will give you the selected breed from the <form:select
...
//do stuff
...
}
I hope my answer gave you a general idea.