今天在做react 前后端请求的时候,发现有个@RequestBody 不能获取map ,查阅了一下get/post请求,记录一下,方便查阅。
一、POST请求
1、 @RequestParam方式:
前端,需要用qs.stringify(data):
ceshi = ()=>{
let data = {
// "idd": "f6588b4d3a274d599c8696e3a2e89579",
// "name":"水"
idd: 'Fred',
lastName: 'Flintstone'
};
// alert()
axios.post(`${base}/t-stu/testWarpper`,
qs.stringify({
idd: 'f6588b4d3a274d599c8696e3a2e89579',
lastName: 'Flintstone'
})
)
.then((response)=> {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
}
后台@RequestParam 获取参数:
@ResponseBody
@RequestMapping(value="/testWarpper",method = RequestMethod.POST)
public Map testWarpper(@RequestParam("idd") String sid){
Map map = new HashMap<>();
QueryWrapper queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("stuid",paramMap.get("idd").toString());
queryWrapper.eq("stuid",sid);
// queryWrapper
List list = tStuMapper.selectList(queryWrapper);
map.put("result",list);
return map;
}
2、@RequestBody方式
前端代码:
ceshi = ()=>{
let data = {
// "idd": "f6588b4d3a274d599c8696e3a2e89579",
// "name":"水"
idd: 'f6588b4d3a274d599c8696e3a2e89579',
lastName: 'Flintstone'
};
// alert()
axios.post(`${base}/t-stu/testWarpper`, data
)
.then((response)=> {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
}
后台代码:
@ResponseBody
@RequestMapping(value="/testWarpper",method = RequestMethod.POST)
public Map testWarpper(@RequestBody(required = false) Map paramMap){
Map map = new HashMap<>();
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.eq("stuid",paramMap.get("idd").toString());
// queryWrapper.eq("stuid",sid);
// queryWrapper
List list = tStuMapper.selectList(queryWrapper);
map.put("result",list);
return map;
}
二、GET请求的方式
1.@RequestParam方式
前端:
ceshi = ()=>{
let data = {
// "idd": "f6588b4d3a274d599c8696e3a2e89579",
// "name":"水"
idd: 'f6588b4d3a274d599c8696e3a2e89579',
lastName: 'Flintstone'
};
// alert()
axios.get(`${base}/t-stu/testWarpper`,{params:data}
)
.then((response)=> {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
}
后台:
@ResponseBody
@RequestMapping(value="/testWarpper",method = RequestMethod.GET)
public Map testWarpper(@RequestParam("idd") String sid){
Map map = new HashMap<>();
QueryWrapper queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("stuid",paramMap.get("idd").toString());
queryWrapper.eq("stuid",sid);
// queryWrapper
List list = tStuMapper.selectList(queryWrapper);
map.put("result",list);
return map;
}
}
2.@ModelAttribute方式,用于接收多个参数的dto实体
前端:(react 有做代理处理)
后台:
总结:
测试了axios.get不能用@RequestBody获取,能用@RequestParam获取。axios.post 可以用@RequestBody获取且不需要qs.stringify序列化,直接传对象就可以了。post请求后台用@RequestParam()获取的时候,前端需要用qs.stringify序列化所传递的参数