这边文章主要是用于记录一下,在前后端分离开发的情况下,存在接口参数的映射。Spring家族提供很多参数的映射的注解,今天着重了解一下@RequestBody和@RequestParam我踩的坑。
@RequestParam
语法
value:参数名
required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值
(1)映射方式一
@RequestMapping("/demo")
public ResponseData demo(@RequestParam Map<String, Object> map)
$.ajax({
type: "post",
url: "/demo",
data: {"name": "zhangsan", "age": "31"}
dataType: "json",
success: function (resp) {
}
});
当前这种情况可以直接写成 demo(String name, String age),个人习惯我比较喜欢比较喜欢讲参数映射Map集合,就算后期接口参数变动,我也不用修改接口。
(2)映射方式二
@RequestMapping("/demo")
public ResponseData demo(@RequestParam(value="name",required=true,defaultValue="hello")String name, String age)
$.ajax({
type: "post",
url: "/demo",
data: {"name": "zhangsan", "age": "31"}
dataType: "json",
success: function (resp) {
}
});
后端接口给name一个默认值为 “hello”
(3)错误演示
@RequestMapping("/demo")
public ResponseData demo(@RequestParam(value="name",required=true,defaultValue="hello")String name, String age)
$.ajax({
type: "post",
url: "/demo",
data: {"name": "zhangsan", "age": "31"}
dataType: "json",
contentType: "application/json",
success: function (resp) {
}
});
结果:
总结:仔细观察ajax请求设置【contentType: “application/json”】,所以导致映射失败。@RequestParam用来处理 Content-Type 为 application/x-www-form-urlencoded 编码的内容,Content-Type默认为该属性。
如果将@RequestParam 替换 @RequestBody时,出现400了,注意参数根本不是json数据
更改ajax
```javascript
$.ajax({
type: "post",
url: "/demo",
data: JSON.stringify({"name":"张三", "age": 23})
dataType: "json",
contentType: "application/json",
success: function (resp) {
}
});
@RequestBody
(1)映射方式一 映射集合
@RequestMapping("/saveRole")
public ResponseData saveRole(@RequestBody List<RoleEntity> roleEntities)
$.ajax({
type: "post",
url: "/demo",
data: JSON.stringify(对象数组)
dataType: "json",
contentType: "application/json",
success: function (resp) {
}
});
(1)映射方式二 映射对象(对象中包括对象)
@RequestMapping("/saveRole")
public ResponseData saveRole(@RequestBody RoleEntity roleEntities)
$.ajax({
type: "post",
url: "/demo",
data: JSON.stringify({"name":"张三", "user":{"username":"xxxx"}})
dataType: "json",
contentType: "application/json",
success: function (resp) {
}
});