如何 select 表单中的集合中的实体? Spring MVC 和 Thymeleaf

How to select entities from collection in form? Spring MVC and Thymeleaf

CompanySet 中有一些 User 个实体,所有用户都存储在数据库中。我想 select 一些用户使用 HTML 形式的 multiple-select。使用 Thymeleaf 和 Spring(MVC,引导)。

我完全不知道应该使用什么。我试过@InitBinder,Spring Core Converter,但没有任何效果。 问题:@Controller 在 bindingResult.hasErrors():

上失败

@Controller

@RequestMapping(value = { "/add" }, method = { RequestMethod.POST })
public String saveNew(@Validated @ModelAttribute("company") Company company, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors())

公司bean

public class Company {
    private Set<User> users = new HashSet<User>();

百里香叶 HTML 形式

<form th:object="${company}">
<select th:field="*{users}" multiple="multiple">
    <option th:each="user : ${allUsers}" th:value="${user.id}" th:text="${user.email}"></option>
</select>

实现这个多重select的正确方法是什么?

您可以使用此代码

<form th:object="${company}">
<select th:field="*{users}" multiple="multiple">
    <option th:each="user : ${allUsers}" th:value="${{user}}" th:text="${user.email}"></option>
</select>

(在 th:value 中查找双 {{}})。

现在您需要这样的格式化程序:

@Component
public class UserFormatter implements Formatter<User> {

@Autowired
private UserService userService;

@Override
public Dia parse(String text, Locale locale) throws ParseException {
    return userService.findById(Long.valueOf(text));
}

@Override
public String print(User object, Locale locale) {
    return String.valueOf(object.getId());
}