迭代JSP中的Enum常量

Dón*_*nal 13 java enums jsp scriptlet

我有一个这样的Enum

package com.example;

public enum CoverageEnum {

    COUNTRY,
    REGIONAL,
    COUNTY
}
Run Code Online (Sandbox Code Playgroud)

我想在JSP中迭代这些常量而不使用scriptlet代码.我知道我可以用这样的scriptlet代码做到这一点:

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

但是如果没有scriptlet,我能实现同样的目标吗?

干杯,唐

Ted*_*ngs 7

如果您正在使用Spring MVC,您可以通过以下语法祝福来实现您的目标:

 <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>
Run Code Online (Sandbox Code Playgroud)

其中您的模型属性(即要填充的bean /数据实体)命名为cluster,并且您已使用名为clusterTypes的枚举值数组填充模型.该<form:error>部分非常可选.

在Spring MVC中,您也可以clusterTypes像这样自动填充到您的模型中

@ModelAttribute("clusterTypes")
public MyClusterType[] populateClusterTypes() {
    return MyClusterType.values();
}
Run Code Online (Sandbox Code Playgroud)


Gar*_*our 5

如果您使用标记库,则可以将代码封装在EL函数中.所以开始标记将成为:

<c:forEach var="type" items="${myprefix:getValues()}">
Run Code Online (Sandbox Code Playgroud)

编辑:回应讨论一个适用于多个枚举类型的实现,只是勾勒出这个:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)