spring 将 <form:select> 标记与地图一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9210733/
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
Use <form:select> tag with a map
提问by Batman
Is there a way to map the data inside a map to tag?
I have a map Map<String, Integer>in my code.
Is there a way to map the option labels to the Stringin the map and the Integerto the option values?
有没有办法将地图内的数据映射到标签?Map<String, Integer>我的代码中有一张地图。有没有办法将选项标签映射到地图String中的 和Integer选项值?
回答by The Awnry Bear
The <form:options>tag supports what you want right out of the box, using the itemsattribute. You can do something like this:
该<form:options>标签使用items属性支持您开箱即用的功能。你可以这样做:
LinkedHashMap<Integer, String> states = new LinkedHashMap<Integer, String>();
states.put(1, "Alabama");
states.put(2, "Alaska");
states.put(3, "Arizona");
states.put(4, "Arkansas");
states.put(5, "California");
And so on. Then in your form:
等等。然后以您的形式:
<form:select path="state">
<form:options items="${states}" />
</form:select>
That will be rendered to something like:
这将被渲染为:
<select name="state">
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">California</option>
</select>
回答by Snowy Coder Girl
See the Spring form:selectand form:optionsdocumentation. Use items, itemValue, and itemLabelas needed.
请参阅 Spring form:select和form:options文档。根据需要使用items、itemValue和itemLabel。
<form:select path="myFormVariable">
<form:option value="0" label="Select One" />
<form:options items="${myCollection}" itemValue="propertyToUseAsValue" itemLabel="propertyToUseAsDisplay" />
</form:select>

