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


问题内容

我已经阅读了所有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');
    }
});

我如何通过控制器接受呢?最好不必创建自定义对象,而只希望能够使用简单的数据类型,但是,如果我需要自定义对象来简化事情,那么我也可以。

为了帮助您入门:

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

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

编辑:

我有更多示例代码,但是我无法使其正常工作,我在这里缺少什么?

选择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);
        }
    });

控制器方法:

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

这将导致以下异常:

org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型’application
/ json’

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


问题答案:

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

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可以将用数字索引的属性绑定到Lists,将用字符串索引的属性绑定到Maps。您在这里需要自定义对象,因为@RequestParam它不支持复杂类型。所以你有了:

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

    ... getters, setters ...
}

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

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