码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot 获取前端传递Json的几种方法

时间:2020-03-18 13:21:25      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:response   style   print   gif   font   ajax   val   content   throw   

一、Json对象+@RequestBody接收

var val = {id: 1, name: "小明"};
$.ajax({
    url: "/getJson",
    dataType: "JSON",
    type: "post",
    contentType: ‘application/json;charset=UTF-8‘,
    data: JSON.stringify(val),
    success: function (msg) {
        console.log(msg)
    }
})

 

后端获取参数:Map<String,Object>

@PostMapping("/getJson")
@ResponseBody
public Map<String,Object> getJsonVal(@RequestBody Map<String,Object> user) {
    System.out.println("user = " + user.get("id"));
    System.out.println("user = " + user.get("name"));
    return user;
}

后端获取参数:对象

@PostMapping("/getJson")
@ResponseBody
public User getJsonVal(@RequestBody User user) {
    return user;
}

二、传JSON对象

var val = {"id": 1, "name": "小明"};
$.ajax({
    url: "/getJson",
    dataType: "JSON",
    type: "post",
    // contentType: ‘application/json;charset=UTF-8‘, //不能加
    data: val,
    success: function (msg) {
        console.log(msg)
    }
})

后端获取参数

@PostMapping("/getJson")
@ResponseBody
public User getJsonVal(@RequestParam("id") String id,@RequestParam("name") String name) {
    User user = new User();
    user.setId(Integer.parseInt(id));
    user.setName(name);
    return user;
}

三、json集合+@RequestBody接收

var val = [{"id": 1, "name": "小明"},{"id": 2, "name": "小红"}];
$.ajax({
    url: "/getJson",
    dataType: "JSON",
    type: "post",
    contentType: ‘application/json;charset=UTF-8‘, //不能加
    data: JSON.stringify(val),
    success: function (msg) {
        console.log(msg)
    }
})

后端获取参数

@PostMapping("/getJson")
@ResponseBody
public List<User> getJsonVal(@RequestBody List<User> user) throws IOException {
    for(User user2 : user){
        System.out.println("user2 = " + user2);
    }
    return user;
}

 

SpringBoot 获取前端传递Json的几种方法

标签:response   style   print   gif   font   ajax   val   content   throw   

原文地址:https://www.cnblogs.com/xuanjinya/p/12516623.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!