Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

enums

jsp

jstl

el

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>
like image 595
kasdega Avatar asked Jul 25 '11 21:07

kasdega


1 Answers

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>
like image 159
BalusC Avatar answered Sep 25 '22 16:09

BalusC