Spring MVC获取请求体的json
作者:Bright Xu
前端ajax部分
前端发送ajax请求
let data = {
id:2,
serial: "万物简史"
}
$.ajax({
url: "/payment/create",
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
success: function(result) {
console.log(result)
}
})
后端控制层部分
后端控制层使用@RequestBody
获取请求体的数据
@PostMapping("/create")
public CommonResult<Object> create(@RequestBody Payment payment) {
log.info("" + payment);
int result = paymentService.create(payment);
log.info("插入结果" + result);
if (result > 0) {
return new CommonResult<>(200, "插入数据库成功", result);
}
return new CommonResult<>(444, "插入失败");
}
相关实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
private Long id;
private String serial;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
private Integer code;
private String message;
private T data;
public CommonResult(Integer code, String message) {
this(code, message, null);
}
}
最终HTTP报文
HTTP请求报文数据
POST http://[::1]:8001/payment/create HTTP/1.1
Host: [::1]:8001
Connection: keep-alive
Content-Length: 32
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.74
Content-Type: application/json
Origin: http://[::1]:8001
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://[::1]:8001/
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,pt;q=0.5
{"id":2,"serial":"万物简史"}
HTTP服务响应报文数据
HTTP/1.1 200
Content-Type: application/json
Date: Thu, 04 Mar 2021 08:17:50 GMT
Keep-Alive: timeout=60
Connection: keep-alive
Content-Length: 55
{"code":200,"message":"插入数据库成功","data":1}