【发布时间】:2021-11-21 06:04:03
【问题描述】:
一个“老师”可以有几个指定的“科目”来教授:
public class Teacher {
private int id;
private String firstName;
private String lastName;
...
private List<Subject> subjects;
}
在 HTML 视图中,用户可以为老师选择一门或多门科目并发送 POST 请求:
<select class="form-control" id="subjects" name="subjects" size="5" multiple required>
<option th:each="subject: ${allSubjects}"
th:value="${subject.id}"
th:text="${subject.name}"
th:selected="${teacher.subjects.contains(subject)}">
</option>
</select>
处理此请求的控制器:
@PostMapping("/update")
public String update(@ModelAttribute("teacher") Teacher teacher) {
logger.debug("Received update data: {}", teacher);
teacherService.update(teacher);
return "redirect:/teachers";
}
这是正在传递的 POST 请求:
我希望 Spring 采用 subject.id 并将它们作为主题列表注入到教师中。 但我得到了例外:
BindException
org.springframework.validation.BeanPropertyBindingResult:
1 errors Field error in object 'teacher' on field 'subjects': rejected value [2,4]; codes [typeMismatch.teacher.subjects,typeMismatch.subjects,typeMismatch.java.util.List,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teacher.subjects,subjects];
arguments []; default message [subjects]]; default message [Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.List' for property 'subjects'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'ua.com.foxminded.university.model.Subject' for property 'subjects[0]': no matching editors or conversion strategy found]
我仔细阅读了我的问题的前 50 个 google 结果,代码应该可以工作,但不能。我一定是错过了什么。
【问题讨论】:
标签: java spring spring-mvc thymeleaf