问题描述
有人可以告诉我,我需要在< form:select>
路径属性及其用途中指定什么?实际上我需要了解下拉列表中所选项目的值是如何传递给控制器的?
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?
推荐答案
说你有一个model(例如Dog), Dog
有各种属性:
name
age
品种
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>
如你所见,我选择了品种
属性为选择
,因为我不希望用户输入他想要的任何品种,我想要他从列表中选择(在这种情况下 allBreeds
,控制器将传递给视图)。
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).
在< form:select>
我用路径
告诉spring必须选择绑定到 Dog
模型的品种
。
In the <form:select>
I've used path
to tell spring that the select has to bind to the breed
of the Dog
model.
我还使用< form:options>
来填充选项,其中包含品种
属性的所有可用选项。
I've also used <form:options>
to fill the select with all the options available for the breed
attribute.
< form:select>
很聪明,如果它正在处理填充的模型(即 Dog
从数据库中获取或使用默认品种值 - 它会自动从列表中选择正确选项。
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.
这篇关于什么是< form:select path>在春季标签用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!