1. Ambiguous handler methods mapped for 오류
문제
@GetMapping("/{postId}")
public ... getPost(@PathVariable Long postId) {
...
}
@GetMapping("/{communityName}")
public ... getPost(@PathVariable String communityName) {
...
}
Ambiguous handler methods mapped for '/posts/13':
{public org.springframework.http.ResponseEntity
com....PostController.getPost(java.lang.String,int,int),
public org.springframework.http.ResponseEntity
com.newsfeed.cider.domain.post.controller.PostController.getPost(java.lang.Long)}
- Spring이 두 메서드 중에서 어떤 것을 호출해야 할지 결정 할 수 없음
/posts/{postId} 와 /posts/{communityName} 유사한 경로로 코딩
해결 - 정규 표현식 사용
@GetMapping("/{postId:\\d+}")
public ... getPost(@PathVariable Long postId) {
...
}
@GetMapping("/{communityName:[a-zA-Z]+}")
public ... getPost(@PathVariable String communityName) {
...
}
Long 타입 메서드에만 숫자를 허용하도록 명시적인 패턴 추가
- 다른 형태의 경로가 들어오면
String 타입 메서드가 처리하도록 추가
- 숫자(0-9)만 허용 :
@GetMapping("/posts/{postId:\\d+}")
- 나머지 모든 문자열 패턴 허용 :
@GetMapping("/posts/{postId}") (이런식으로도 가능)
해결 - 경로 변경
@GetMapping("/{postId}")
public ... getPost(@PathVariable Long postId) {
...
}
@GetMapping("/community/{communityName}")
public ... getPost(@PathVariable String communityName) {
...
}
2. Request method 'POST' not supported
문제
@PostMapping("/posts/{postId}/comments/{parentId}")
public ... createComment(@PathVariable Long postId,
@PathVariable(required = false) Long parentId,
@RequestBody CommentCreateRequest request) {
...
}
@GetMapping("/posts/{postId}/comments")
public ... getComments(@PathVariable Long postId) {
...
}
Resolved
[org.springframework.web.HttpRequestMethodNotSupportedException:
Request method 'POST' is not supported]
Resolved 오류가 나는 상황
parentId 넣지 않았을 때 GET Method부분으로 스프링이 인식
해결
@PostMapping("/posts/{postId}/comments/{parentId}")
public ... createComment(@PathVariable Long postId,
@RequestParam(required = false) Long parentId,
@RequestBody CommentCreateRequest request) {
...
}
PathVariable → RequestParam 으로 변경
- 보안상 문제가 없다고 GPT님께서 말씀해주심