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?
JSTL stands for JSP Standard Tag Library. JSTL is the standard tag library that provides tags to control the JSP page behavior. JSTL tags can be used for iteration and control statements, internationalization, SQL etc.
JSP lets you even define your own tags (you must write the code that actually implement the logic of those tags in Java). JSTL is just a standard tag library provided by Sun (well, now Oracle) to carry out common tasks (such as looping, formatting, etc.).
Install JSTL Library To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses the library.
The <c:out> tag is similar to JSP expression tag, but it can only be used with expression. It will display the result of an expression, similar to the way < %=... % > work.
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.
There isn't in JSTL. However many frameworks provide such additional tags:
Struts2 - <s:select>
Spring MVC - <form:select>
<h:selectOneMenu>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With