Post请求中@RequestParam和@RequestBody的使用

您所在的位置:网站首页 php获取post参数 Post请求中@RequestParam和@RequestBody的使用

Post请求中@RequestParam和@RequestBody的使用

2023-05-18 20:21| 来源: 网络整理| 查看: 265

使用

如何在一个@RestController方法中混合使用@RequestParam和@RequestBody呢?就像这样的代码:

@PostMapping("/scanRecord") public Response scanRecord(@RequestParam("t") int type, @RequestBody ScanRecord scanRecord) { System.out.println("type="+type); System.out.println(JSON.toJSONString(scanRecord)); return Response.ok(); } 核心概念:

@RequestBody用来接收http post请求的body,前端传入序列化好的json数据,后端可以解析为json对象(Content-Type需要指定为 application/json)。

@RequestParam用来接收请求url?后面的参数,或者Content-Type为multipart/form-data、application/x-www-form-urlencoded时的http body数据。

所以,如果想要在@RestController的一个方法中,同时接收@RequestParam和@RequestBody数据,前端应该这样用:

混用 @RequestBody, @RequestParam : function post() { // json 数据;RequestBody接收 var data = { id: 1000, pn:'华为手机' }; // /?t=1 @RequestParam 接口 axios.post('http://localhost:8080/api/scanRecord?t=1', data).then(function (res) { }).catch(function (error) { }); } axios Post (application/json) 提交 function post() { var data = { id: 1000, pn:'华为手机' }; axios.post('http://localhost:8080/api/scanRecord?t=1', data).then(function (res) { }).catch(function (error) { }); } axios post提交multipart/form-data、application/x-www-form-urlencoded数据 //form-data方式 function post() { var data = new FormData(); data.append("id", 1000); data.append("pn", '华为手机'); axios.post('http://localhost:8080/api/scanRecord?t=1', data).then(function (res) { }).catch(function (error) { }); } //x-www-form-urlencoded方式 function encodeData(data) { var args = []; for(var attr in data) { args.push(attr+"=" + data[attr]); } return encodeURI(args.join("&")); } function post() { var data = { id: 1000, pn:'华为手机' }; axios.post('http://localhost:8080/api/scanRecord?t=1', encodeData(data)).then(function (res) { }).catch(function (error) { }); }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3