java 枚举值作为下拉列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7591776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:37:11  来源:igfitidea点击:

Enum values as dropdown list

javajspspring-mvcenumsel

提问by BambooBlunder

I am facing an issue populating a dropdown list from Enum class values. My enum class code is:

我面临从 Enum 类值填充下拉列表的问题。我的枚举类代码是:

package abc.xyz.constants;

public enum StateConstantsEnum
{
           NEWYORK("NY"), 
            FLORIDA("FL"), 
            CALIFORNIA("CA"), 

    private String fullState;

    private StateConstantsEnum( String s )
    {
        fullState = s;
    }

    public String getState()
    {
        return fullState;
    }
}

I want populate dropdown list with NEWYORK, FLORIDA and CALIFORNIA. I am creating and adding the list to Spring model this way:

我想用纽约、佛罗里达和加利福尼亚填充下拉列表。我正在以这种方式创建列表并将其添加到 Spring 模型中:

List<StateConstantsEnum> stateList = new ArrayList<StateConstantsEnum>( Arrays.asList(StateConstantsEnum.values() ));

model.addAttribute("stateList", stateList);

Then I am trying to populate the dropdown in JSP using:

然后我尝试使用以下方法填充 JSP 中的下拉列表:

<select name="${status.expression}" name="stateLst" id="stateLst">
    <option value=""></option>
        <c:forEach items="${stateList}" var="option">
                <option value="${option}">
                    <c:out value="${option.fullState}"></c:out>
                </option>
        </c:forEach>
</select>

But I am getting an exception "Exception created : javax.el.PropertyNotFoundException: The class 'abc.xyz.constants.StateConstantsEnum' does not have the property 'fullState'."

但我收到一个异常“异常创建:javax.el.PropertyNotFoundException:类'abc.xyz.constants.StateConstantsEnum'没有属性'fullState'。”

How do I fix this problem? Help much appreciated

我该如何解决这个问题?非常感谢帮助

回答by Joe

fullStateis private, getState()is the accessor.

fullState是私有的,getState()是访问者。

<c:out value="${option.state}"></c:out>

Or rename your getter to getFullstate().

或者将您的 getter 重命名为getFullstate().

回答by Slifer

in your JSP you can use a like that :

在您的 JSP 中,您可以使用类似的方法:

<form:select path="*">
  <form:options items="${stateList}" itemLabel="fullState"  />
</form:select>

it will extract all element in your liste (stateList) and if you dont specify an itemLabel and itemValue, it'll take your enums values of course you have to set your getter to getFullState,and declare springmvc tags in your page

它将提取您的列表(stateList)中的所有元素,如果您不指定 itemLabel 和 itemValue,它将采用您的枚举值,当然您必须将 getter 设置为 getFullState,并在您的页面中声明 springmvc 标签