Discussions

Web tier: servlets, JSP, Web frameworks: Iterating enums using EL

  1. Iterating enums using EL (1 messages)

    While the world of EL revolves around getXXX and setXXX pattern, an astute observer would notice that it doesn't wear well with most of Java Core APIs. It seems to be less talked about observation that Java Core APIs use XXX pattern for accessing and mutating properties. For example, java.nio.Buffer defines following methods.

    void limit(int newLimit)
    int limit()
    void position(int newPosition)
    int position()
    ...

    Hence, System.currentTimeMillis() Object.hasCode() and not System.getCurrentTimeMillis and Object.getHashCode()

    It becomes a problem particularly if one tries to use EL for iterating through the values of an Enum type. A concrete Enum class would have following methods.

    class Action {
      public static final Action GET = new Action("GET");
      public static final Action POST = new Action("POST");
      public static final Action PUT = new Action("PUT");
      public static final Action DELETE = new Action("DELETE");
      
      public static Action[] values() {
        ...
      }

      public String name() {
      }

      public int ordinal() {
      }
    }

    It be nice to have the following.
    <c:forEach var="action" items="${actions}">
     <option value="<c:out value="${action.ordinal}"/>"
     <c:if test="${currency == 'GET'}">
      selected="selected"
     </c:if>
     ><c:out value="${action}"/></option><br>
    </c:forEach>

    However, this doesn't work because the don't follow getXXX pattern. Yet, I foolishly ask if there is a way iterate enums in EL?
    In fact, I propose that EL should allow backquote evalution so the following code could be written as.

    <c:forEach var="action" items="`Action.values()`">
     <option value="<c:out value="`action.ordinal()`"/>"
     <c:if test="${currency == 'GET'}">
      selected="selected"
     </c:if>
     ><c:out value="`action.name()`"/></option><br>
    </c:forEach>
  2. Iterating enums using EL[ Go to top ]

    Try looking at OGNL, which does what you want and is part of some web frameworks, like Tapestry.

    I would not expect JSTL EL to change, though. Until it does, write code that follows the JavaBean specs, and if you need to interact with legacy code that does not follow the getter/setter pattern, write an adapter bean:

    public class SystemAdapter() {
        public long getCurrentTimeMillis() {
            return System.currentTimeMillis();
        }
    }