Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Validation 如何从表单中的集合中选择实体?Spring MVC和Thymeleaf_Validation_Spring Mvc_Thymeleaf_Spring Validator - Fatal编程技术网

Validation 如何从表单中的集合中选择实体?Spring MVC和Thymeleaf

Validation 如何从表单中的集合中选择实体?Spring MVC和Thymeleaf,validation,spring-mvc,thymeleaf,spring-validator,Validation,Spring Mvc,Thymeleaf,Spring Validator,公司在集合中有一些用户实体,所有用户都存储在数据库中。我想使用HTML格式的multiple select选择一些用户。使用Thymeleaf和Spring(MVC,Boot) 我完全不知道该用什么。我试过@InitBinder和Spring-Core转换器,但都没用。 问题:@控制器在bindingResult上失败。hasErrors(): @控制器 @RequestMapping(value = { "/add" }, method = { RequestMethod.POST }) pu

公司
集合
中有一些
用户
实体,所有用户都存储在数据库中。我想使用HTML格式的
multiple select
选择一些用户。使用Thymeleaf和Spring(MVC,Boot)

我完全不知道该用什么。我试过@InitBinder和Spring-Core转换器,但都没用。 问题:@控制器在bindingResult上失败。hasErrors():

@控制器

@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>();
上市公司{
private Set users=new HashSet();
Thymeleaf 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>

如何实现此多选的正确方法是什么?

您可以使用此代码

<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());
}
@组件
公共类UserFormatter实现格式化程序{
@自动连线
私人用户服务;
@凌驾
public Dia parse(字符串文本、区域设置)引发ParseException{
返回userService.findById(Long.valueOf(text));
}
@凌驾
公共字符串打印(用户对象、区域设置){
返回字符串.valueOf(object.getId());
}

在我看来很好,您会遇到什么错误?如果它已经被选中怎么办?我们如何使用th:selected=“?”