Java spring 标签中的 <form:select path> 是做什么用的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22860381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is <form:select path> in spring tag used for?
提问by Shivayan Mukherjee
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?
有人可以告诉我我需要在<form:select>
path 属性中指定什么以及它的用途吗?实际上我需要了解如何将下拉列表中所选项目的值传递给控制器?
回答by Shay Elkayam
Say you have a model (Dog for example), a Dog
has various attributes:
name
age
breed
假设您有一个模型(例如 Dog),aDog
具有多种属性:
name
age
品种
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 typewhatever breed he want, I want him to choose from a list(allBreeds
in this case, which the controller will pass to the view).
如您所见,我选择了breed
属性为 a select
,因为我不希望用户输入他想要的任何品种,我希望他从列表中进行选择(allBreeds
在这种情况下,控制器将传递给看法)。
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:select>
我用path
告诉弹簧选择具有绑定到breed
了的Dog
模型。
I've also used <form:options>
to fill the select with all the options available for the breed
attribute.
我还习惯使用<form:options>
可用于该breed
属性的所有选项来填充选择。
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.
这<form:select>
是智能的,如果它正在处理填充模型(即Dog
从数据库中获取或具有默认品种值) - 它会自动从列表中选择“正确”选项。
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.
我希望我的回答能让你有一个大致的了解。