《SpringMvc》---实现JSON数据交互

前言

  • 现在企业中好多项目都用Json传送数据,因为Json在企业开发中已经作为通用的接口参数类型,并且Json数据在页面(客户端)解析很方便。下面是Json的定义形式。
var obj={”name”:”张三”,”age”:12}
Json数据解析形式:obj.name

现在有两种需求:

  • 前台Jsp向Handler中传递Json数据,Handler向前台返回Json数据。
  • 前台Jsp向Handler中传递键值对形式,Handler返回json数据。

第一种,前台传json,Handler返回的也是Json

Js代码

function requestjson(){
    $.ajax({
        type:'post',
        url:'${pageContext.request.contextPath }/requestJson.action',
        contentType:'application/json;charset=utf-8',
        data:'{"name":"张三","age":12}',//json串
        success:function(data){
            alert(data.name);
        }
    });
}

Handler代码

@ResponseBody
@RequestMapping("/requestJson")
public Student requestJson(@RequestBody Student student){
    System.out.println(student);
    return student;
}

第二种,前台传递键值对,后台返回的是Json

Js代码

function responsejson(){
    $.ajax({
        type:'post',
        url:'${pageContext.request.contextPath }/responseJson.action',
        data:'name=张三&age=12',//key/value
        success:function(data){
            alert(data.name);
        }
    });
}

Handler代码

@ResponseBody
@RequestMapping("/responseJson")
public  Student responseJson(Student student) throws Exception{
    System.out.println(student);
    return student;
}

小结

  • 这是利用JQuery的Ajax来实现前后台传递Json数据的,再Handler中,如果想接受前台传递过来的Json数据,那么在形参前面加上@RequestBody注解,如果Handler也想返回Json数据,那么可以在方法上加上@ResponseBody注解。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值