从枚举jsp下拉

时间:2017-09-26 06:11:17

标签: java spring jsp enums dropdown

您可以帮助我获取以下代码吗?我试图将ENUM值设置为下拉列表,但下拉列表不显示任何内容。

create.jsp

    <select name="labOwner" name="labOwner" id="labOwner">
      <option value="Select"></option>
        <c:forEach var="labOwner" items="${labOwner}">
            <li>${labOwner}</li>
        </c:forEach>
    </select>

LabController.java

    @RequestMapping(value = "/lab/labOwner")
public ModelAndView getPages(){
    List<LabOwner> labOwner = new ArrayList<LabOwner>( Arrays.asList(LabOwner.values() ));
    ModelAndView model = new ModelAndView("create");
    model.addObject("labOwner", labOwner);

    return model;
}

LabOwner.java

public enum LabOwner {
    G_ONLY("G"),
    D_ONLY("D"),
    GS("S/D ");

    private String labOwner;

    LabOwner(String labOwner) {
        this.labOwner = labOwner;
    }

    public String getLabOwner() {
        return labOwner;
    }

1 个答案:

答案 0 :(得分:0)

您可以使用spring form标记绑定您的媒体资源:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<form:select path="labOwnerBeanPropertyNameHere" id="labOwner">
     <c:forEach var="labOwnerValue" items="${labOwner}">
         <form:option value="${labOwnerValue}">${labOwnerValue}</form:option>
     </c:forEach>
</form:select>

请注意,您希望在labOwner列表中显示每个项目的值,而不是整个列表。

此外,您的控制器代码可以简化为:

@GetMapping("/lab/labOwner")
public String getPages(Model model){
    model.addAttribute("labOwner", 
                       new ArrayList<LabOwner>(Arrays.asList(LabOwner.values());
    return "create";
}

最后,请查看Project Lombok,并为@Getter课程使用Enum注释。