views:

3318

answers:

3

Hi,

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

+3  A: 

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;
 }
}
Garth Gilmour
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?
Don
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; }}
Garth Gilmour
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.
Don
A: 

hi, what is "myprefix:" in example above?

I think `myprefix` is the prefix used (in a JSP) to refer to the class in which `getValues` is defined.
Don
+1  A: 

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();
}
Ted Pennings