zoukankan      html  css  js  c++  java
  • 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<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;
    }
    复制代码
  • 相关阅读:
    bzoj1318[spoj 744] Longest Permutation
    bzoj2146 Construct
    bzoj2448 挖油
    bzoj3961[WF2011]Chips Challenge
    bzoj4152[AMPPZ2014] The Captain
    AtCoder Regular Contest 076E Coneected?
    Codeforces 748D Santa Claus and a Palindrome
    bzoj3572[HNOI2014]世界树
    SQL SERVER 字段统一补0方法
    SSRS运行report builder报错 的解决方案
  • 原文地址:https://www.cnblogs.com/dk2557/p/13876679.html
Copyright © 2011-2022 走看看