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

这篇博客讲述了如何在SpringMVC中使用@RequestBody和@ResponseBody注解将前端发送的JSON数据绑定到Controller中的泛型对象容器。通过在配置文件中添加MappingJacksonHttpMessageConverter并引入Jackson库,解决了'415 Unsupported Media Type'的错误。对于Spring 3.1.2及更高版本,只需包含Jackson 2的依赖即可自动处理JSON转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值