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

一、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

@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 出现 Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported!
问题点1:

如果Content-Type设置为“application/x-www-form-urlencoded;charset=UTF-8”无论是POST请求还是GET请求都是可以通过这种方式成功获取参数,但是如果前端POST请求中的body是Json对象的话,会报上述错误。

请求中传JSON时设置的Content-Type 如果是application/json或者text/json时,JAVA中request.getParameter("")怎么也接收不到数据。这是因为,Tomcat的HttpServletRequest类的实现类为org.apache.catalina.connector.Request(实际上是org.apache.coyote.Request)。

问题点2:

当前端请求的Content-Type是Json时,可以用@RequestBody这个注解来解决。@RequestParam 底层是通过request.getParameter方式获得参数的,换句话说,@RequestParam 和request.getParameter是同一回事。因为使用request.getParameter()方式获取参数,可以处理get 方式中queryString的值,也可以处理post方式中 body data的值。所以,@RequestParam可以处理get 方式中queryString的值,也可以处理post方式中 body data的值。@RequestParam用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST。

@RequestBody接受的是一个json对象的字符串,而不是Json对象,在请求时往往都是Json对象,用JSON.stringify(data)的方式就能将对象变成json字符串。

总结:

前端请求传Json对象则后端使用@RequestParam;

前端请求传Json对象的字符串则后端使用@RequestBody。

你可能感兴趣的:(springboot,js)