How to create a drop down menu from an enum?

2020-07-24 06:31发布

How could I display the values of enum structure in JSP? I use the Spring MVC to implement my project.

Many thanks!

public enum ProjectStatusEnum {
    INITIAL(0,"Initial"),ONGOING(1,"Ongoing"),CLOSED(2,"Closed");

    private int value;
    private String key;

    ProjectStatusEnum(int value , String key){
        this.value=value;
        this.key = key;
    }
    public int getValue() {
        return value;
    } 
    public void setValue(int value) {
        this.value = value;
    }  
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }

}

2条回答
走好不送
2楼-- · 2020-07-24 06:49

Add the enum values in an attribute of your request:

// ProjectStatusEnum.values() return an array of ProjectStatusEnum
request.setAttribute("enum", ProjectStatusEnum.values());

And finally, within your JSP:

<ul class="dropdownmenu">
    <c:forEach items="${enum}" var="entry">
        <li>${entry.key} (${entry.value})</li> <!-- for example -->
    </c:forEach>
</ul>
查看更多
Luminary・发光体
3楼-- · 2020-07-24 07:05
  1. Define in your ModelAttribute class the variable to bind to the type of your ENUM class

     public class YourCommand implements Serializable{
        private ProjectStatusEnum yourVariable; 
        /*setter and getter of yourVariable*/
     }
    
  2. In the controller, put an instance of YourCommand yourCommand into Model

  3. On your jsp page,

    
    
    <form:form method="POST" modelAttribute="yourCommand" ...> 
        <form:select path="yourVariable" cssErrorClass="yourErrorClass">
           <option>Select Project Status</option>
           <form:options itemLabel="key" />
        </form:select>
    </form:form>
    
查看更多
登录 后发表回答