Spring RestController @PathVariable 사용하기

cozzin·2024년 5월 28일
0
    @GetMapping("/{userId}")
    fun findUserById(@PathVariable userId: Long): ResponseEntity<User> {
        val user = userService.findUserById(userId)
        return user?.let {
            ResponseEntity.ok(it)
        } ?: ResponseEntity.notFound().build()
    }

이런식으로 작성할 수 있다.
@PathVariable은 어떤 것을 기준으로 매핑되는지 궁금해졌다.

GPT쌤이랑 얘기해보니 name 기준으로 매핑된다고 한다. 순서 기준이아니다. 그래서 다음과 같이 사용해도 정상적으로 매핑된다.

@GetMapping("/users/{userId}/posts/{postId}")
fun getUserPost(
    @PathVariable postId: Long,
    @PathVariable userId: Long
): ResponseEntity<PostResponse> {
    val post = postService.findPostByUserIdAndPostId(userId, postId)
    return post?.let {
        ResponseEntity.ok(it)
    } ?: ResponseEntity.notFound().build()
}
profile
Software Engineer

0개의 댓글