Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating over Enum constants in JSP

I have an Enum like this

package com.example;

public enum CoverageEnum {

    COUNTRY,
    REGIONAL,
    COUNTY
}

I would like to iterate over these constants in JSP without using scriptlet code. I know I can do it with scriptlet code like this:

<c:forEach var="type" items="<%= com.example.CoverageEnum.values() %>">
    ${type}
</c:forEach>

But can I achieve the same thing without scriptlets?

Cheers, Don

like image 554
Dónal Avatar asked Sep 26 '08 20:09

Dónal


People also ask

How do I iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

What is enum constant?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

How is enum used in Java?

Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. A Java enumeration is a class type.


1 Answers

If you're using Spring MVC, you can accomplish your goal with the following syntactic blessing:

 <form:form method="post" modelAttribute="cluster" cssClass="form" enctype="multipart/form-data">
   <form:label path="clusterType">Cluster Type
      <form:errors path="clusterType" cssClass="error" />
   </form:label>
   <form:select items="${clusterTypes}" var="type" path="clusterType"/>
 </form:form>

where your model attribute (ie, bean/data entity to populate) is named cluster and you have already populated the model with an enum array of values named clusterTypes. The <form:error> part is very much optional.

In Spring MVC land, you can also auto-populate clusterTypes into your model like this

@ModelAttribute("clusterTypes")
public MyClusterType[] populateClusterTypes() {
    return MyClusterType.values();
}
like image 139
Ted Pennings Avatar answered Sep 28 '22 18:09

Ted Pennings