采用json数据格式实现SpringMVC和ajax的交互

客户端发起ajax请求: 请求参数的形式有哪些?
1. json对象格式
2. json 串格式
3. key=value字符串格式 (推荐使用这一种)

Controller向客户端响应的数据格式:
1. json对象
2. 文本

客户端发起ajax请求,请求参数为json对象

那么controller方法中形参该如何绑定?
此时的参数绑定和提交的key=value字符串格式是一样的绑定方式。
image.png

$(function () {
        $.ajax({
            url: "${pageContext.request.contextPath}/findItems2.do",
            type: "post",
//            data: {name: "手机", price: 500.0, detail: "好手机"},
            data: "name=手机&price=500&detail=好手机",
            dataType: "json",

            success: function (msg) {
                alert(msg);
            }
        })
    });

客户端发起ajax请求,但是参数是json串格式(了解)

那么controller的方法中形参该如何绑定?
给处理器适配器配置一个json转换器

    /*
     如果请求参数是json串  ,那么在ajax方法中得要加一个参数
     contentType:"application/json;charset=utf-8";
     */
    $(function () {
        $.ajax({
            url: "${pageContext.request.contextPath}/findItems3.do",
            type: "post",
            contentType: "application/json;charset=utf-8",
            data: '{"name": "手机", "price": 500.0, "detail": "好手机"}',
            dataType: "json",

            success: function (msg) {
//                alert(msg);
                // 将json对象转换成json串
                alert(JSON.stringify(msg));
                alert(msg.name + "--" + msg.price + "--" + msg.detail);
            }
        })
    });

配置json转换器:

<!-- 注解适配器 -->
<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 />来代替处理器适配器和处理器映射器, 那么就不需要配置json转换器 , 会去自动加载.
image.png

SpringMVC支持json的jar包

image.png

两个注解的使用

@RequestBody

如果ajax请求Controller的时候, 传递的是json串,那么在Controller方法的pojo形参前面加上该注解,会将json串中的属性值自动注入到pojo中的属性中。

@Controller
public class JsonController {

    @RequestMapping("/findItems3.do")
    @ResponseBody
    public Items findItems2(@RequestBody Items items) {

        return items;
    }
}

实体类:
image.png

@ResponseBody(重要)

将Controller方法返回的pojo对象转换成json对象响应给客户端

注意: SpringMVC跟ajax交互的时候, Controller方法的返回值最好是 POJO类型, Map或者List集合类型.

@Controller
public class JsonController {
    @RequestMapping("/findItems2.do")
    @ResponseBody
    public Items findItems(Items items) {

        return items;
    }
}

传值成功:
image.png

回调成功的信息:
image.png

完整代码地址

image.png

https://github.com/menglanyingfei/SSMLearning/tree/master/SSM

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值