- POST method로 전달된 데이터들을 자바 객체로 변환하려면 @RequestBody 어노테이션을 사용한다.
@PostMapping("/club") // localhost:8090/club
public String register(@RequestBody TravelClubCdo travelClubCdo){
return clubService.registerClub(travelClubCdo);
}
단, 전달된 데이터의 키가 다르거나 없으면 객체 안의 해당 필드는 비어있으니 확인하자.
- GET method 로 전달된 URL에서 특정 path를 캡처하고 싶을 때 @PathVariable 어노테이션을 사용한다.
@GetMapping("/club/{clubId}")
public TravelClub find(@PathVariable String clubId){
return clubService.findClubById(clubId);
}
만약 http://localhost:8090/club/f5c382b0-5c30-4d78-8dfc-03496ad01516 라는 url으로 get 요청을 보냈을 때, f5c382b0-5c30-4d78-8dfc-03496ad01516 부분이 clubId로 전달된다.
하지만 여기서 주의 할 부분이 있다. 밑의 코드를 살펴보자.
@GetMapping("/club/{clubId}")
public TravelClub find(@PathVariable String clubId){
return clubService.findClubById(clubId);
}
@GetMapping("/club/{name}")
public List<TravelClub> findByName(@PathVariable String name){
return clubService.findClubsByName(name);
}
서버를 실행시키고 해당 url에 get 요청을 보내면 다음과 같은 오류가 발생한다.
java.lang.IllegalStateException: Ambiguous handler methods mapped for '/club/f5c382b0-5c30-4d78-8dfc-03496ad01516'
이 오류는 조건에 맞는 url을 가진 @GetMapping annotation이 여러 개여서 발생한다. 이 url을 처리할 method가 find 인지 findByName인지 모호하다는 것이다.
해결 방법 중 하나는 parameter를 이용하여 get 요청을 보내는 것이다. @RequestParam 어노테이션을 이용한다.
@GetMapping("/club") // localhost:8090/club?name=javaClub
public List<TravelClub> findByName(@RequestParam String name){
System.out.println(name);
return clubService.findClubsByName(name);
}
또는 restAPI의 url depth를 늘려서 새로운 url을 정의하는 것인데, depth가 너무 깊어지는 것은 직관적이지 않으니 너무 복잡해지지 않게 잘 선택해야 할 것 같다.
'Web Programming > Spring' 카테고리의 다른 글
Spring Security Architecture (0) | 2024.12.28 |
---|---|
Spring Request Mapping 매개변수 오류 (1) | 2024.12.20 |
Spring Data JPA (0) | 2024.12.17 |
DispatcherServlet의 위치는? (0) | 2024.12.08 |
STS Spring Boot application can't resolve the org.springframework.boot package 오류 (0) | 2022.06.02 |