How to display all values of an enum as <option> elements?
Asked Answered
I

1

5

I need to display all values of an enum as <option> elements. I have achieved this using scriptlets:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib prefix="errors" tagdir="/WEB-INF/tags/jostens/errors" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

...
<%
        Class<?> c = CarrierCode.class;
        for (Object carrier : c.getEnumConstants()) {
            CarrierCode cc = (CarrierCode) carrier;
            StringBuilder sb = new StringBuilder();
            Formatter formatter = new Formatter(sb, Locale.US);
            out.print(formatter.format("<option value='%s'>%s</option>\n", cc.getMfCode(), cc.name()));
        }
%>
...

However, I would like to implement it using JSTL/EL code instead. How can I do it?

UPDATE:

Spring has a much easier way to do this now. First add the spring frame work tags <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> then if you just declare a select where the variable in path is an Enum, spring automagically finds the other elements.

<form:select path="dataFormat.delimiter" class="dataFormatDelimiter">
    <form:options items="${dataFormat.delimiter}"/>
</form:select>
Ingeborgingelbert answered 25/7, 2011 at 21:30 Comment(2)
@BalusC Thanks for the edit much clearer now.Ingeborgingelbert
Possible duplicate of iterating over Enum constants in JSPJenisejenkel
M
7

Create a ServletContextListener implementation which puts the enum values in the application scope during webapp startup so that it's available in EL by ${carrierCodes}. This class is reuseable for all other things you'd like to do once during webapp's startup.

@WebListener
public class Config implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        event.getServletContext().setAttribute("carrierCodes", CarrierCode.values());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // NOOP
    }

}

Note that I used Enum#values() instead of the clumsy Class#getEnumConstants() method. It returns an array of all enum values.

Then, in JSP, just use JSTL <c:forEach> to iterate over it.

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="carrierCode">
  <c:forEach items="${carrierCodes}" var="carrierCode">
    <option value="${carrierCode.mfCode}">${carrierCode}</option>
  </c:forEach>
</select>
Mashe answered 25/7, 2011 at 21:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.