如何在一个@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数据,前端应该使用 application/json的方式传入@RequestBody接收的对象,并且在url?后带上@RequestParam需要接收的参数。 前端js使用axios提交的话,是这样的:
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) { }); }