SpringBoot-Controller接收参数

在springboot中使用注解接收参数

获取参数的几种常用注解

  • @PathVariable: 如果是url/{param}这种restful风格的话,使用这种形式接收

    1
    2
    3
    4
    5
    6
    @ApiOperation("根据id获取")
    @GetMapping("/{id}")
    public JsonResult<Tag> getTagById(@PathVariable("id") int id) {
    Tag tag = tagService.getTagById(id);
    return new JsonResult<>(tag);
    }
  • @RequestParam: 获取多个参数的时候常用, 直接写参数名

  • @RequestBody: 与@RequestParam类似,将注解的所有参数转换为一个对象,比如DTO对象

    1
    2
    3
    4
    5
    @DeleteMapping("/resident")
    public JsonResult<Integer> deleteResidentTag(@ApiParam(name = "residentTagDTO", value = "居民tag实体", required = true) @RequestBody ResidentTagDTO residentTagDTO){
    int deleteResidentTag = residentTagService.deleteResidentTag(residentTagDTO);
    return new JsonResult<>(deleteResidentTag);
    }

使用对象直接获取参数

可以接收一个pojo来作为参数,然后通过get方法直接把需要的参数取出来即可

1
2
3
4
5
6
7
8
/**
* 添加用户2
* @param userInfo
*/
@PostMapping("/createUser2")
public void createUser2(UserInfo userInfo){
userService.createUser(userInfo.getTel(),userInfo.getPassWord());
}

推荐: 使用Map接收参数

也是使用@RequestBody注解,使用Map

可以使用在没有必要写一个DTO但是参数复杂的情况

1
2
3
4
5
6
@PostMapping("/createUserByMap")
public void createUserByMap(@RequestBody Map<String,Object> reqMap){
String tel = reqMap.get("tel").toString();
String pwd = reqMap.get("pwd").toString();
userService.createUser(tel,pwd);
}