Springmvc json数据交互

1 Springmvc json数据交互

1.1 @RequestBody

作用:@RequestBody 注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容转换 为json、xml等格式的数据并绑定到controller方法 的参数 上。

1.2 @ResponseBody

作用:该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据,如json、xml等,通过response响应给客户端。

1.3 请求json,响应json的实现

1.3.1 环境准备

Springmvc默认用MappingJacksonHttpMessageConverter对json数据进行转换,需要加入jackson的包,如下:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.5</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
1.3.2 配置json转换器

在注解适配器中加入messageConverters

<!--注解适配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
        <list>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
        </list>
        </property>
    </bean>

注意:如果使用<mvc:annotation-driven /> 则不用定义上边的内容。

1.3.3 controller编写
// 商品修改提交json信息,响应json信息
    @RequestMapping("/editItemSubmit_RequestJson")
    public @ResponseBody Items editItemSubmit_RequestJson(@RequestBody Items items) throws Exception {
        System.out.println(items);
        //itemService.saveItem(items);
        return items;

    }
1.3.4 页面js方法编写

引入 js:

//请求json响应json
    function request_json(){
        $.ajax({
            type:"post",
            url:"${pageContext.request.contextPath }/item/editItemSubmit_RequestJson.action",
            contentType:"application/json;charset=utf-8",
            data:'{"name":"测试商品","price":99.9}',
            success:function(data){
                alert(data);
            }
        });
    }

猜你喜欢

转载自blog.csdn.net/fd2025/article/details/80453549