Can I access the values of an enum class from a JSP using EL?

*爱你&永不变心* 提交于 2019-12-12 08:36:17

问题


I have an enum class USState. I would like to iterate through the states in a JSP.

Is it possible to access a list of USStates without first setting such a list as an attribute? It seems that something as static as an enum should always be available, but I can't figure out how to do it.

Here's what I'm looking for: (except working)

<c:forEach var="state" items="${USState.values}" >
    <option value="${state}">${state}</option>
</c:forEach>

回答1:


You can also consider to wrap it in a Javabean like follows:

package com.stackoverflow.q2240722;

public class StateBean {

    public State[] getValues() {
        return State.values();
    }

}

This way it's accessible by <jsp:useBean>:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<jsp:useBean id="stateBean" class="com.stackoverflow.q2240722.StateBean" />

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2240722</title>
    </head>
    <body>
        <select>
            <c:forEach items="${stateBean.values}" var="state">
                <option value="${state}">${state}</option>        
            </c:forEach>
        </select>
    </body>
</html>



回答2:


You will have to create a list somewhere on your backing code and pass it as a model parameter. Preferably in an ServletContextListener (as advised by BalusC) and put it in the ServletContext (i.e. application scope):

servletContext.setAttribute("statesList", YourEnum.values());



回答3:


Note that you can also use a scriptlet (I don't think it's too harmful in such a simple case):

<c:forEach var="state" items="<%= USState.values() %>" >

(USState should be either fully qualified or imported using <%@ page import = "..." %>



来源:https://stackoverflow.com/questions/2240722/can-i-access-the-values-of-an-enum-class-from-a-jsp-using-el

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!