1.使用@RequestBody注解:
前端ajax传送数据的时候,需要指明contentType参数为:contentType: "application/json"
@RequestBody注解接收的参数是Json对象的字符串,所以需要用JSON.stringify()将对象转换为字符串
否则得不到数据
定义接口:
//后台接口:
@RequestMapping(value = "/addUnearthedAnnexRecords")
public Result addUnearthedAnnexRecords(@RequestBody UnearthedAnnexRecordsRequest unearthedAnnexRecordsRequest) {
return Result;
}
//实体类:
@Data
public class UnearthedAnnexRecordsRequest {
private Long mid;
private String name;
private String description;
}
//前端ajax请求:
$.ajax({
url: '/addUnearthedAnnexRecords',
type: "POST",
data: JSON.stringify({
"mid":mid,
"name":name,
"description":description
}),
dataType: "json",
contentType: "application/json",
success: function (result) {
//do something ...
},
error: function (xhr, ajaxOptions, thrownError) {
//console.log(thrownError); //alert any HTTP error
return false;
}
});
2.不使用@RequestBody注解:
不需要特别指定contentType参数,服务端接收key-value形式参数
定义接口:
//后台接口:
@RequestMapping(value = "/addUnearthedAnnexRecords")
public Result addUnearthedAnnexRecords(UnearthedAnnexRecordsRequest unearthedAnnexRecordsRequest) {
return Result;
}
//实体类:
@Data
public class UnearthedAnnexRecordsRequest {
private Long mid;
private String name;
private String description;
}
//前端ajax请求:
$.ajax({
url: '/addUnearthedAnnexRecords',
type: "POST",
data: {
"mid":mid,
"name":name,
"description":description
},
dataType: "json",
//contentType: "application/json",
success: function (result) {
//do something ...
},
error: function (xhr, ajaxOptions, thrownError) {
//console.log(thrownError); //alert any HTTP error
return false;
}
});
需要注意的问题:
即便没有特别限制请求类型,但是在使用@RequestBody注解的时候,通过Get方式请求接口,会报错,原因是因为格式类型为:xxx?mid=xx&name=xxx&description=xxx
即便是Post请求,也需要在Header里面指定contentType=application/json
我想,在接口测试的时候可能会遇到该问题。