如何使用Spring和Thymeleaf在下拉列表中显示所有可能的枚举值? [英] How to display all possible enum values in a dropdown list using Spring and Thymeleaf?
本文介绍了如何使用Spring和Thymeleaf在下拉列表中显示所有可能的枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有枚举属性的域对象,我希望在该对象的表单中显示一个包含所有可能枚举值的下拉列表。想象一下以下对象:
I have a domain object that has an enum property and I want to display a dropdown list with all possible enum values in the form for this object. Imagine the following object:
public class Ticket {
private Long id;
private String title;
private State state;
// Getters & setters
public static enum State {
OPEN, IN_WORK, FINISHED
}
}
在我的控制器中,我有一个为此对象呈现表单的方法:
In my controller I have a method that renders a form for this object:
@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>
稍后应将其转换为以下内容:
Later it should be transformed to something like this:
<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>
如何创建选择标记?所选值也应自动映射到票证,以便我可以在控制器中执行以下操作:
How can I create the select tag? The selected value should also be mapped to the ticket automatically so that I can do something like this in the controller:
@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在下拉列表中显示所有可能的枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文