最近一直在学习Spring Boot,今天将其中的从前台过来的参数传递总结一下。
1.Get取参数
1.1@PathVariable
需要在path中取相应的参数时可以使用这个注解。
@RequestMapping("/get/user/{id}")
public String getUserId(@PathVariable(value = "id") String id) {
log.info("id: {}", id);
return "id: " + id;
}
测试结果:
1.2@RequestParameter
需要通过url中的方式来传递参数的话我们通过@RequestParameter来进行传递
@RequestMapping("/get/userName")
public String getUserName(@RequestParam("name") String name) {
log.info("userName : {}", name);
return "UserName: " + name;
}
测试结果:
2.Post 传递参数
2.1@RequestParameter
在post中也可以通过RequestParameter来进行参数的传递,注意的一点就是header中的Content-Type不能为application/json,不然会报错。
@RequestMapping(value = "/post/requestParam/getUserName", method = RequestMethod.POST)
public String postUserName(@RequestParam(value = "name") String name) {
log.info("userName : {}", name);
return "UserName: " + name;
}
测试结果:
2.2@RequestBody
- 第一种用法是转换成map
@RequestMapping(value = "/post/requestBody/getUserName", method = RequestMethod.POST)
public String postUserNameByRequestBody(@RequestBody Map<String, Object> map) {
String name = (String) map.get("name");
log.info("userName : {}", name);
return "UserName: " + name;
}
测试结果
- 第二种用法是转换成实体类
@RequestMapping(value = "/post/requestBody/object/getUserName")
public String postUserNameByObject(@RequestBody User user) {
String name = user.getName();
log.info("userName : {}", name);
return "UserName: " + name;
}
git地址:https://gitee.com/xuzhangRIchard/spring-boot-parameter-transfer