迭代JSP中的Enum常量
我有一个像这样的枚举
package com.example; public enum CoverageEnum { COUNTRY, REGIONAL, COUNTY }
我想在JSP中迭代这些常量而不使用scriptlet代码。 我知道我可以用这样的scriptlet代码做到这一点:
<c:forEach var="type" items=""> ${type}
但是如果没有scriptlet,我可以实现同样的目标吗?
干杯,唐
如果你正在使用Spring MVC,你可以通过以下语法祝福来实现你的目标:
Cluster Type
其中您的模型属性(即要填充的bean /数据实体)被命名为cluster,并且您已使用名为clusterTypes的值的枚举数组填充模型。
部分非常可选。
在Spring MVC中,您还可以像这样自动将clusterTypes
填充到模型中
@ModelAttribute("clusterTypes") public MyClusterType[] populateClusterTypes() { return MyClusterType.values(); }
如果使用标记库,则可以将代码封装在EL函数中。 所以开始标记将变为:
编辑:回应讨论一个适用于多个枚举类型的实现,只是勾勒出这个:
public static > Enum [] getValues(Class klass) { try { Method m = klass.getMethod("values", null); Object obj = m.invoke(null, null); return (Enum [])obj; } catch(Exception ex) { //shouldn't happen... return null; } }