iterating over Enum constants in JSP

后端 未结 2 1394
长情又很酷
长情又很酷 2021-01-04 03:52

I have an Enum like this

package com.example;

public enum CoverageEnum {

    COUNTRY,
    REGIONAL,
    COUNTY
}

I would like to iterate

相关标签:
2条回答
  • 2021-01-04 04:34

    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();
    }
    
    0 讨论(0)
  • 2021-01-04 04:37

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题