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

2

10

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?

Eavesdrop answered 10/2, 2010 at 13:39 Comment(1)
You should really clarify the term "manually" more here. You should also clarify what's wrong with c:forEach. It dynamically iterates over the list as well without that you need to know the amount of items beforehand.Oxy
R
6

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

Riesman answered 10/2, 2010 at 13:49 Comment(3)
No? He just didn't want to manually iterate through the list. Or we must all have another interpretation of "manually". Anyway, to complete the list, in JSF there's a h:selectOneMenu.Oxy
I'll use Struts2. I forgot that I could use the struts tags, without using the Struts framework.Eavesdrop
@Oxy - I understood that 'manually' means 'by c:forEach', but it could well mean anything else.Riesman
O
16

Certainly, in JSTL (just drop jstl-1.2.jar in /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.

Here's a demo how the <c:forEach> can then be used:

<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.

See also:

Oxy answered 10/2, 2010 at 13:47 Comment(0)
R
6

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

Riesman answered 10/2, 2010 at 13:49 Comment(3)
No? He just didn't want to manually iterate through the list. Or we must all have another interpretation of "manually". Anyway, to complete the list, in JSF there's a h:selectOneMenu.Oxy
I'll use Struts2. I forgot that I could use the struts tags, without using the Struts framework.Eavesdrop
@Oxy - I understood that 'manually' means 'by c:forEach', but it could well mean anything else.Riesman

© 2022 - 2024 — McMap. All rights reserved.