![](/img/trans.png)
[英]How to pass a list from the view to the controller in Spring MVC with thymeleaf?
[英]Sping MVC, Thymeleaf, POST request, how to pass list of objects to controller
一個“老師”可以有幾個指定的“科目”來教:
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`s 作為主題列表注入到老師中。 但我得到了例外:
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 個谷歌結果,代碼應該可以工作,但它沒有。 我肯定錯過了什么。
首先是錯誤的注釋 - 你不要在帖子內部使用@ModelAttribute
,而是在帖子的彈簧控制器中隱含的@RequestBody
。
除此之外,您發送的不是老師實體,而是老師DTO,它不會包含您展示的老師實體所具有的所有字段(集合)。 這意味着您應該接收不同的類(TeacherDTO),然后將其正確轉換為教師實體,然后在數據庫中更新
我想這是一個更新表格,所以它需要一個對象老師作為輸入。 嘗試這個
<form th:object="${teacher}" method="post">
<select class="form-control" th:field="*{subjects}" id="subjects" name="subjects" size="5" multiple required>
<option th:each="subject: ${allSubjects}"
th:value="${subject.id}"
th:text="${subject.name}"
th:selected="*{subjects.contains(subject)}">
</option>
</select>
</form>
最后,我在處理項目的另一部分時找到了解決方案。 我試圖將 Lecture 對象傳遞給控制器,Lecture 包含學生組列表。 每個組有 2 個字段:id 和 name。 首先我們實現一個格式化程序
public class GroupFormatter implements Formatter<Group> {
@Override
public Group parse(String text, Locale locale) throws ParseException {
Group group=new Group();
if (text != null) {
String[] parts = text.split(",");
group.setId(Integer.parseInt(parts[0]));
if(parts.length>1) {
group.setName(parts[1]);
}
}
return group;
}
@Override
public String print(Group group, Locale locale) {
return group.toString();
}
}
在 MVCConfig 中注冊格式化程序
@Override
public void addFormatters(FormatterRegistry registry) {
GroupFormatter groupFormatter=new GroupFormatter();
registry.addFormatter(groupFormatter);
}
我們從 POST 請求中得到正確的格式:
groups=[4:VM-08, 5:QWE-123]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.