如何使用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";
}