如何使用Spring和Thymeleaf在下拉列表中显示所有可能的枚举值?
我有一个具有枚举属性的域对象,并且我想以该对象的形式显示一个包含所有可能的枚举值的下拉列表。想象以下对象:
public class Ticket { private Long id;
private String title;
private State state;
// Getters & setters
public static enum State {
OPEN, IN_WORK, FINISHED
}
}
在我的控制器中,我有一个方法呈现此对象的形式:
@RequestMapping("/tickets/new")public String showNewTicketForm(@ModelAttribute Ticket ticket) {
return "tickets/new";
}
模板如下所示:
<form th:action="@{/tickets}" method="post" th:object="${ticket}"> <input type="text" th:field="*{title}" />
<select></select>
</form>
稍后,应将其转换为如下形式:
<form action="/tickets" method="post"> <input type="text" name="title" />
<select name="state">
<option>OPEN</option>
<option>IN_WORK</option>
<option>FINISHED</option>
</select>
</form>
如何创建选择标签?所选值还应该自动映射到票证,以便我可以在控制器中执行以下操作:
@RequestMapping(value = "/tickets", method = RequestMethod.POST)public String createTicket(@Valid Ticket ticket) {
service.createTicket(ticket);
return "redirect:/tickets";
}
回答:
您可以这样做:
<select> <option th:each="state : ${T(com.mypackage.Ticket.State).values()}"
th:value="${state}"
th:text="${state}">
</option>
</select>
以上是 如何使用Spring和Thymeleaf在下拉列表中显示所有可能的枚举值? 的全部内容, 来源链接: utcz.com/qa/399208.html