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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:05:35  来源:igfitidea点击:

How can I produce a select tag using JSTL or Standard Actions in a JSP

javahtmljspjstl

提问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

There isn't in JSTL. However many frameworks provide such additional tags:

JSTL 中没有。然而,许多框架提供了这样的附加标签:

回答by BalusC

Certainly, in JSTL(just drop jstl-1.2.jarin /WEB-INF/lib) there's the c:forEachtag. You'll only have to convert the (old fashioned) Enumerationto a modern Listor perhaps Enumif it's hardcoded in Java. You can if necessary grab Collections#list()for this if the Enumerationis 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, sessionor applicationscopes — of which the applicationscope is the most straightforward choice, as a list of countries is supposed to be an application wide constant. You could use a ServletContextListenerto load it once and put in application scope on application's startup. The Countryis in this example just a Javabean (model) class with at least two properties.

${countries}应该是指一个List<Country>Country[]已被放置在任何的pagerequestsessionapplication作用域-它的application范围是最简单的选择,因为国家的名单应该是一种应用广泛的常数。您可以使用 aServletContextListener加载一次并在应用程序启动时放入应用程序范围。的Country是在本例中只是一个JavaBean(模型)具有至少两个属性的类。

See also:

也可以看看: