iterating over Enum constants in JSP

2019-02-12 06:55发布

问题:

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

回答1:

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();
}


回答2:

If you are using Tag Libraries you could encapsulate the code within an EL function. So the opening tag would become:

<c:forEach var="type" items="${myprefix:getValues()}">

EDIT: In response to discussion about an implementation that would work for multiple Enum types just sketched out this:

public static <T extends Enum<T>> Enum<T>[] getValues(Class<T> klass) {
    try { 
        Method m = klass.getMethod("values", null);
        Object obj = m.invoke(null, null);
        return (Enum<T>[])obj;
    } catch(Exception ex) {
        //shouldn't happen...
        return null;
    }
}