@PathVariable
- @PathVariable 能使傳過(guò)來(lái)的參數(shù)綁定到路由上,這樣比較容易寫(xiě)出restful api. 舉個(gè)栗子:
@GetMapping(value = "/{id}")
public ApiResponse getUser(@PathVariable String id) {
return ApiResponse.getDefaultResponse(userService.getUserById(id));
}
這個(gè)接口可通過(guò)get請(qǐng)求http://xxx/00655853a1fb11e989b80242ac1292831來(lái)獲取用戶(hù)的數(shù)據(jù),00655853a1fb11e989b80242ac1292831既是getUser的方法參數(shù)又是@GetMapping的路由.如果方法參數(shù)不想寫(xiě)成和路由一樣的應(yīng)該怎么辦?再舉個(gè)栗子:
@GetMapping(value="/{id}")
public ApiResponse getUser(@PathVariable("uid") String id) {
return ApiResponse.getDefaultResponse(userService.getUserById(id));
}
@PathVariable("uid")這樣可以了,就是這么簡(jiǎn)單.
@RequestParam
- @RequestParam和@PathVariable的區(qū)別是請(qǐng)求時(shí)當(dāng)前參數(shù)是在url路由上還是在請(qǐng)求的body上,舉個(gè)栗子:
@PostMapping(value = "")
public ApiResponse postUser(@RequestParam(value = "phone", required = true) String phone, String userName) {
userService.create(phone, userName);
return ApiResponse.getDefaultResponse();
}
這個(gè)接口的請(qǐng)求url這樣寫(xiě):http://xxx?phone=150184796xx,也就是說(shuō)被@RequestParam修飾的參數(shù)最后通過(guò)key=value的形式放在http請(qǐng)求的Body傳過(guò)來(lái),對(duì)比@PathVariable就很容易看出兩者的區(qū)別了.
@RequestBody
- @RequestBody能把簡(jiǎn)單json結(jié)構(gòu)參數(shù)轉(zhuǎn)換成實(shí)體類(lèi),舉個(gè)栗子:
@PostMapping(value = "")
public ApiResponse postUser(@RequestBody User user){
System.out.print(user.getAge());
return ApiResponse.getDefaultResponse();
}
參數(shù): {"id": "00655853a1fb11e989b80242ac1292831", "user": "測(cè)試", "name": "name", "age": 18}
注意請(qǐng)求的content type要設(shè)置為application/json.