Vue+SpringBoot 前后台JSON 交互(亲测踩坑)

本文详细介绍了前端VUE如何向后端SpringBoot发送请求,并展示了两种接收数据的方法:一是通过@RequestBody接收JSON格式的数据;二是通过HttpServletRequest解析请求体为JSON对象。这两种方式在实际开发中非常实用,帮助开发者理解前后端数据交互的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话不多说,直接上代码,前端VUE的请求方法

这样写在浏览器看到的参数可能有点奇怪

不要慌,服务端仍然可以接收

 

 

Springboot端代码有两种接收方式

1、通过@RequestBody 接收json

    @RequestMapping(value = "/modifyInfo1", method = RequestMethod.POST)
    public String get(@RequestBody Map map) {
        String param1 = (String) map.get("param1");
        String param2 = (String) map.get("param2");
        System.out.println(param1+"----"+param2);
        return param1 + ";" + param2;
    }
    

2、通过Request获取

@ResponseBody
@RequestMapping(value = "/request/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public String getByRequest(HttpServletRequest request) {

    //JSONObject
    JSONObject jsonParam = this.getJSONParam(request);

    return jsonParam.toJSONString();
}

public JSONObject getJSONParam(HttpServletRequest request){
    JSONObject jsonParam = null;
    try {
        // 获取输入流
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

        // 数据写入Stringbuilder
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = streamReader.readLine()) != null) {
            sb.append(line);
        }
        jsonParam = JSONObject.parseObject(sb.toString());
        System.out.println(jsonParam.toJSONString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return jsonParam;
}

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值