Java 如何在 JSP 中使用 JSTL 或标准操作生成选择标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2237135/
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
How can I produce a select tag using JSTL or Standard Actions in a JSP
提问by Eric Wilson
I want to make a select tag in a JSP, where the options are an Enumeration (for example, all US States). Is their a tag in JSTL or a standard tag that can do this, without manually iterating through the list?
我想在 JSP 中创建一个选择标记,其中选项是一个枚举(例如,所有美国州)。它们是 JSTL 中的标记还是可以执行此操作的标准标记,而无需手动遍历列表?
采纳答案by Bozho
回答by BalusC
Certainly, in JSTL(just drop jstl-1.2.jarin /WEB-INF/lib
) there's the c:forEach
tag. You'll only have to convert the (old fashioned) Enumeration
to a modern List
or perhaps Enum
if it's hardcoded in Java. You can if necessary grab Collections#list()
for this if the Enumeration
is to be obtained from an unchangeable 3rd party API.
当然,在JSTL(只需将jstl-1.2.jar放入/WEB-INF/lib
)中有c:forEach
标签。您只需将(老式)Enumeration
转换为现代的,List
或者Enum
如果它是用 Java 硬编码的。如果要从不可更改的 3rd 方 API获取Collections#list()
,您可以在必要时获取此信息Enumeration
。
Here's a demo how the <c:forEach>
can then be used:
这是一个如何<c:forEach>
使用的演示:
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.code}" ${param.country eq country.code ? 'selected' : ''}>${country.name}</option>
</c:forEach>
</select>
The ${countries}
should refer a List<Country>
or Country[]
which has been put in any of the page
, request
, session
or application
scopes — of which the application
scope is the most straightforward choice, as a list of countries is supposed to be an application wide constant. You could use a ServletContextListener
to load it once and put in application scope on application's startup. The Country
is in this example just a Javabean (model) class with at least two properties.
本${countries}
应该是指一个List<Country>
或Country[]
已被放置在任何的page
,request
,session
或application
作用域-它的application
范围是最简单的选择,因为国家的名单应该是一种应用广泛的常数。您可以使用 aServletContextListener
加载一次并在应用程序启动时放入应用程序范围。的Country
是在本例中只是一个JavaBean(模型)具有至少两个属性的类。