扯扯SpringBoot中@PathVariable @RequestParam @RequestBody

@PathVariable

  • @PathVariable 能使传过来的参数绑定到路由上,这样比较容易写出restful api. 举个栗子:
@GetMapping(value = "/{id}")
public ApiResponse getUser(@PathVariable String id) {
    return ApiResponse.getDefaultResponse(userService.getUserById(id));
}

这个接口可通过get请求http://xxx/00655853a1fb11e989b80242ac1292831来获取用户的数据,00655853a1fb11e989b80242ac1292831既是getUser的方法参数又是@GetMapping的路由.如果方法参数不想写成和路由一样的应该怎么办?再举个栗子:

@GetMapping(value="/{id}")
public ApiResponse getUser(@PathVariable("uid") String id) {
    return ApiResponse.getDefaultResponse(userService.getUserById(id));
}

@PathVariable("uid")这样可以了,就是这么简单.

@RequestParam

  • @RequestParam和@PathVariable的区别是请求时当前参数是在url路由上还是在请求的body上,举个栗子:
@PostMapping(value = "")
public ApiResponse postUser(@RequestParam(value = "phone", required = true) String phone, String userName) {
    userService.create(phone, userName);
    return ApiResponse.getDefaultResponse();
}

这个接口的请求url这样写:http://xxx?phone=150184796xx,也就是说被@RequestParam修饰的参数最后通过key=value的形式放在http请求的Body传过来,对比@PathVariable就很容易看出两者的区别了.

@RequestBody

  • @RequestBody能把简单json结构参数转换成实体类,举个栗子:
@PostMapping(value = "")
public ApiResponse postUser(@RequestBody User user){
    System.out.print(user.getAge());
    return ApiResponse.getDefaultResponse();
}

参数: {"id": "00655853a1fb11e989b80242ac1292831", "user": "测试", "name": "name", "age": 18}

注意请求的content type要设置为application/json.

你可能感兴趣的:(扯扯SpringBoot中@PathVariable @RequestParam @RequestBody)