简体   繁体   English

Sping MVC、Thymeleaf、POST 请求,如何将对象列表传递给控制器

[英]Sping MVC, Thymeleaf, POST request, how to pass list of objects to controller

A "teacher" can have several assigned "subjects" to teach:一个“老师”可以有几个指定的“科目”来教:

public class Teacher {
    private int id;
    private String firstName;
    private String lastName;
    ...
    private List<Subject> subjects;
}

In HTML view user can select one ore more subjects for the teacher and send POST request:在 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>

Controller to process this request:处理此请求的控制器:

@PostMapping("/update")
    public String update(@ModelAttribute("teacher") Teacher teacher) {
        logger.debug("Received update data: {}", teacher);
        teacherService.update(teacher);
        return "redirect:/teachers";
    }

Here is the POST request that is being passed:这是正在传递的 POST 请求:

在此处输入图片说明

I expect Spring to take subject.id`s and inject them into teacher as list of subjects.我希望 Spring 将 subject.id`s 作为主题列表注入到老师中。 But I get exception:但我得到了例外:

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]

I carefully read first 50 google results for my question, code should work, but it doesn't.我仔细阅读了我的问题的前 50 个谷歌结果,代码应该可以工作,但它没有。 I must be missing something.我肯定错过了什么。

First of all wrong annotation - u dont use @ModelAttribute inside of the post but rather @RequestBody which is implicit in spring controllers for post.首先是错误的注释 - 你不要在帖子内部使用@ModelAttribute ,而是在帖子的弹簧控制器中隐含的@RequestBody

Other than that what you are sending is not a teacher entity but rather teacherDTO which wont have all the fields (collections) that teacher entity that you showed has.除此之外,您发送的不是老师实体,而是老师DTO,它不会包含您展示的老师实体所具有的所有字段(集合)。 That means you should be receiving a different class (TeacherDTO) and then convert it correctly to teacher entity which you then update in the database这意味着您应该接收不同的类(TeacherDTO),然后将其正确转换为教师实体,然后在数据库中更新

i suppose this is an update form, so it take an object teacher as an input.我想这是一个更新表格,所以它需要一个对象老师作为输入。 try this尝试这个


<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>

Finally I found the solution while working on another part of my project.最后,我在处理项目的另一部分时找到了解决方案。 I tried to pass Lecture object to controller, Lecture contains List of student groups.我试图将 Lecture 对象传递给控制器​​,Lecture 包含学生组列表。 Each group has 2 fields: id and name.每个组有 2 个字段:id 和 name。 First we implement a formatter首先我们实现一个格式化程序

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();
    }
}

Register formatter in MVCConfig在 MVCConfig 中注册格式化程序

@Override
    public void addFormatters(FormatterRegistry registry) {
        GroupFormatter groupFormatter=new GroupFormatter();
        registry.addFormatter(groupFormatter);
    }

And we get the correct format from POST request:我们从 POST 请求中得到正确的格式:

groups=[4:VM-08, 5:QWE-123]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将列表从视图传递到 Spring MVC 和 thymeleaf 中的 controller? - How to pass a list from the view to the controller in Spring MVC with thymeleaf? 在Thymeleaf模板上为POST请求绑定嵌入式对象列表 - Binding embedded List of objects on a Thymeleaf template for a POST request Spring MVC + Thymeleaf 后单 Object 至 Z9BBF373797BF7CF7BA252C8002368 - Spring MVC + Thymeleaf Post Single Object to Controller 如何将对象列表从spring控制器绑定到thymeleaf - how to bind a list of objects from the spring controller to thymeleaf Html 使用 spring mvc 和 thymeleaf 发布请求 - Html post request using spring mvc and thymeleaf 如何在Spring MVC中将LIST从一个控制器传递到另一个控制器 - How to pass LIST from one controller to another controller in spring mvc 将复杂对象列表传递给控制器 - pass list of complex objects to controller 构建一个控制器,该控制器通过表单(Thymeleaf)更改POST请求中的变量 - Building a controller that changes a variable in a POST request via form (Thymeleaf) 无法将对象列表传递给控制器 - Cannot pass list of objects to controller 如何从控制器传递多个模型对象以及如何将所有作为命令对象传递给spring mvc中的form:form? - How to pass multiple model objects from controller and how to pass all as command objects into the form:form in spring mvc?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM