SpringBoot获取前台传递对象的方法
首先说一下@RequestParam和@RequestBoby的区别:
- @RequestParam:请求头参数,常用于get请求。content-type默认为application/x-www-form-urlencoded。即k-v键值对形式
- 所以在postman或apifox中,如果是post请求。需要在boby中选择x-www-form-urlencoded,不能使用json
- 在前台传递中,可以将content-type改为application/json,然后参数改为JSON.stringify(data),才能正确传递
- @RequestBoby:请求体。一般用于处理content-type为application/json类型
- 如果不加注解,则默认application/x-www-form-urlencoded。即k-v键值对形式
SpringBoot获取前台传递对象并不容易,稍有错误就会报错。这里提供一个大致模板方法:
前台代码:
let student = {
id: 1,
name: 'tom',
email: '123@qq.com',
age: 15
};
$('#pojoTest').click(function () {
$.ajax({
url: getContextPath() + `/test/test3`,
type: "post",
data: JSON.stringify(student),
contentType: "application/json;charset=utf-8",
success: function (result) {
console.log(result);
},
});
});
后台代码:
@PostMapping("/test3")
public AjaxResult test3(@RequestBody Student student) {
System.out.println(student);
return AjaxResult.ok("姓名:" + student.getName());
}
- 这里采用的方式就是post请求,前端更改contentType,data改为json,后台添加@RequestBoby注解