使用@RequestBody, @ResponseBody实现前台JSON与对象(或泛型对象容器)的绑定

1. JQuery发送Ajax请求
var array = [{id: '01', name: 'name01'}, {id: '02', name: 'name02'}];
$.ajax({
    type: "PUT",
    url: '/WebTest/user/create/batch',
    data: JSON.stringify(array),
    contentType: 'application/json',
    dataType: 'json',
    success: function() {
        console.log('get response');
    },
});

发送到后台的请求如图:


2. 此处略去${servletName}-servlet.xml中的一些常规配置,如

<mvc:annotation-driven />
<context:component-scan base-package="example" />

3. 我的目标是在SpringMVC的Controller层直接用以下代码,让JSON数据直接绑定到指定泛型的容器中

package example.controller;

@Controller
@RequestMapping("/user")
public class UserController {

    // 省略logger等初始化
   
    @RequestMapping(value = "/create/batch", method = RequestMethod.PUT)
    public String batchCreate(Model model, @RequestBody List<User> list) throws InterruptedException, IOException {
        logger.debug(list.size());
        return index(model);
    }
}

好了,直接运行代码,会遇到“415 Unsupported Media Type”的错误,这是因为还需要其他的配置和依赖包。

4. 解决方案:${servletName}-servlet.xml中添加

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
            </list>
        </property>
    </bean>

这个adapter会自动根据contentType('application/json') 来处理JSON。

最后在pom中添加相关依赖,

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

====第4点 是SpringMVC 3.1.2之前的配置,3.1.2 and later version are more easier to achieve that====

Spring 3.1.2 adds support for automatic conversion to JSON via Jackson 2.x. There isn’t much that you need to do to make it work. You need to be using at least Spring 3.1.2 to have Jackson 2.x support. Add the Jackson 2.x dependencies.

from Spring 3.2.1 version is now incompatible to Jackson FasterXML 2.1.x versions. For Jackson 2, please use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter.

按照Spring官方文档所述,MappingJackson2HttpMessageConverter不需要显式配置,只要classpath中有Jackson 2的依赖即可,即:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.0</version>
        </dependency>

所以xxx-servlet.xml中只需要<mvc:annotation-driven/>即可。

=====Notes:=====

Jackson 2的group id换做fasterxml,不再是Jackson 1的codehaus

"Jackson has a new namescape since version 2.0.0: com.fasterxml.jackson
while it used to be under org.codehaus.jackson until version 1.9.9"

More more NOTE: If you only include the jackson-core artifact and do not include the jackson-databind artifact, your spring requests will return HTTP 406 errors and there will be no indication of what the real problem is.

猜你喜欢

转载自dearls.iteye.com/blog/2076177