2008-09-26 85 views
12

枚举常量我有一个枚举这样循环访问JSP中

package com.example; 

public enum CoverageEnum { 

    COUNTRY, 
    REGIONAL, 
    COUNTY 
} 

我想遍历在JSP这些常量,而无需使用scriptlet代码。我知道我可以用这样的scriptlet代码做到这一点:

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

但我可以做到同样的事情没有小脚本?

干杯, 唐

回答

5

如果您使用的标签库,你可以EL函数内封装代码。因此,开放标签将成为:

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

编辑:在回答关于将多个枚举类型的工作实现的讨论只是勾勒出这样的:如果你使用Spring MVC

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

如果我这样做,这样我就需要定义EL函数每个枚举,这将是一个真正的痛苦。定义一个适用于所有枚举的单个函数(可能通过反射)将是更可取的。但是,在某些JSP taglib中肯定存在这样的函数? – 2008-09-26 20:18:51

7

,你可以用下面的语法祝福达成你的目标:

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

您的模型属性(即豆/数据实体填充)被命名为集群,并且您已经填充日e模型,其中包含名为clusterTypes的枚举数组。 <form:error>部分是非常可选的。

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

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