java 在 JSP 中迭代枚举常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/141611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:11:02  来源:igfitidea点击:

iterating over Enum constants in JSP

javajspenumsscriptlet

提问by Dónal

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:

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

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

But can I achieve the same thing without scriptlets?

但是我可以在没有脚本的情况下实现同样的目标吗?

Cheers, Don

干杯,唐

回答by Ted Pennings

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

如果您使用的是 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>

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.

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

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

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

@ModelAttribute("clusterTypes")
public MyClusterType[] populateClusterTypes() {
    return MyClusterType.values();
}

回答by Garth Gilmour

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

如果您使用标签库,您可以将代码封装在 EL 函数中。所以开始标签将变成:

<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:

编辑:为了回应有关适用于多种 Enum 类型的实现的讨论,只是勾勒出这一点:

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