扯扯SpringBoot中@PathVariable @Requ

2019-08-26  本文已影响0人  marquess

@PathVariable

@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

@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

@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.

上一篇 下一篇

猜你喜欢

热点阅读