iterating over Enum constants in JSP
Asked Answered
H

2

14

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:

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

But can I achieve the same thing without scriptlets?

Cheers, Don

Hirst answered 26/9, 2008 at 20:0 Comment(0)
C
7

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();
}
Corelli answered 4/10, 2010 at 17:9 Comment(0)
P
5

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;
    }
}
Pronation answered 26/9, 2008 at 20:10 Comment(4)
If I do it this way I'd need to define an EL function for each enum, which would be a real pain. Defining a single function that works for all enums (probably via reflection) would be preferable. But surely such a function already exists in some JSP taglib?Bickford
There may well be but I dont know of it, just had a go: 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) { return null; } }Pronation
Nice work. Boy, is that type parameter <T extends Enum<T>> ugly! I'm criticizing the Java generics implementation here, not your code. I've been forced into similar abominations myself. Thanks for the code.Bickford
why not just use klass.getEnumConstants()?Uneasy

© 2022 - 2024 — McMap. All rights reserved.