Spring 3 MVC - 高级数据绑定 - 带有简单对象列表的表单请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3566201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:07:01  来源:igfitidea点击:

Spring 3 MVC - Advanced Data Binding - Form Request with List of Simple Objects

springspring-mvc

提问by walnutmon

I've read through all of the Spring 3 Web docs: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/spring-web.htmlbut have been completely unable to find any interesting documentation on binding more complicated request data, for example, let's say I use jQuery to post to a controller like so:

我已经通读了所有 Spring 3 Web 文档:http: //static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/spring-web.html但完全无法找到任何关于绑定更复杂的请求数据的有趣文档,例如,假设我使用 jQuery 发布到控制器,如下所示:

$.ajax({
    url: 'controllerMethod',
    type: "POST",
    data : {
        people : [
        {
            name:"dave", 
            age:"15"
        } ,
{
            name:"pete", 
            age:"12"
        } ,
{
            name:"steve", 
            age:"24"
        } ]
    },
    success: function(data) {
        alert('done');
    }
});

How can I accept that through the controller? Preferably without having to create a custom object, I'd rather just be able to use simple data-types, however if I need custom objects to make things simpler, I'm fine with that too.

我怎样才能通过控制器接受它?最好不必创建自定义对象,我宁愿能够使用简单的数据类型,但是如果我需要自定义对象来使事情变得更简单,我也可以。

To get you started:

让您开始:

@RequestMapping("/controllerMethod", method=RequestMethod.POST)
public String doSomething() {
    System.out.println( wantToSeeListOfPeople );
}

Don't worry about the response for this question, all I care about is handling the request, I know how to deal with the responses.

不要担心这个问题的回应,我关心的只是处理请求,我知道如何处理回应。

EDIT:

编辑:

I've got more sample code, but I can't get it to work, what am I missing here?

我有更多示例代码,但我无法让它工作,我在这里错过了什么?

select javascript:

选择javascript:

var person = new Object();
    person.name = "john smith";
    person.age = 27;

    var jsonPerson = JSON.stringify(person);

    $.ajax({
        url: "test/serialize",
        type : "POST",
        processData: false,
        contentType : 'application/json',
        data: jsonPerson,
        success: function(data) {
            alert('success with data : ' + data);
        },
        error : function(data) {
            alert('an error occurred : ' + data);
        }
    });

controller method:

控制器方法:

public static class Person {

        public Person() {
        }

        public Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }
        String name;
        Integer age;

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    @RequestMapping(value = "/serialize")
        @ResponseBody
        public String doSerialize(@RequestBody Person body) {
            System.out.println("body : " + body);
            return body.toString();
        }

this renders the following exception:

这会导致以下异常:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported

org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型“应用程序/json”

If the doSerialize() method takes a String as opposed to a Person, the request is successful, but the String is empty

如果 doSerialize() 方法采用 String 而不是 Person,则请求成功,但 String 为空

回答by axtavt

Your jQuery ajax call produces the following application/x-www-form-urlencodedrequest body (in %-decoded form):

您的 jQuery ajax 调用生成以下application/x-www-form-urlencoded请求正文(以 %-decoded 形式):

people[0][name]=dave&people[0][age]=15&people[1][name]=pete&people[1][age]=12&people[2][name]=steve&people[2][age]=24

Spring MVC can bind properties indexed with numbers to Lists and properties indexed with strings to Maps. You need the custom object here because @RequestParamdoesn't support complex types. So, you have:

Spring MVC 可以将数字索引的属性绑定到Lists,将字符串索引的属性绑定到Maps。此处需要自定义对象,因为@RequestParam不支持复杂类型。所以你有了:

public class People {
    private List<HashMap<String, String>> people;

    ... getters, setters ...
}

@RequestMapping("/controllerMethod", method=RequestMethod.POST)        
public String doSomething(People people) {        
    ...
} 

You can also serialize data into JSON before sending them and then use a @RequestBody, as Bozho suggests. You may find an example of this approach in the mvc-showcase sample.

您还可以在发送数据之前将数据序列化为 JSON,然后@RequestBody按照 Bozho 的建议使用 。您可以在mvc-showcase sample 中找到这种方法的示例

回答by Bozho

if you have <mvc:annotation-driven>enabled then:

如果您已<mvc:annotation-driven>启用,则:

@RequestMapping("/controllerMethod", method=RequestMethod.POST)
public String doSomething(@RequestBody List<Person> people) {
    System.out.println( wantToSeeListOfPeople );
}

(List<Person>might not be the structure you would like to obtain, it's just an example here)

List<Person>可能不是您想要获得的结构,这里只是一个示例)

You can try setting the Content-Typeof $.ajaxto be application/json, if it doesn't work immediately.

你可以尝试设置Content-Type$.ajaxapplication/json,如果不立即工作。

回答by Adam Gent

Have a look at Hymanson's spring integration. It is incredible easy to use and powerful.

看看Hymanson的 spring 集成。它非常易于使用且功能强大。

A question/answer on SO that can help guide on this: Spring 3.0 making JSON response using Hymanson message converter

关于 SO 的一个问题/答案可以帮助指导这个问题: Spring 3.0 making JSON response using Hymanson message converter