본문 바로가기
Spring/이론

Spring @PathVariable vs @RequestBody

by JuNo_12 2025. 5. 9.
@GetMapping("/{id}")
    public ResponseEntity<MemoResponseDto> findMemoById(@PathVariable Long id) {

        return new ResponseEntity<>(memoService.findMemoById(id), HttpStatus.OK);
    }

 

여기서는 왜 @RequestBody를 안해줬을까?

 

이 이유는 HTTP GET 요청의 특성과 관련이 있다.

1. GET 요청의 특징

  • GET 방식은 리소스를 "조회"할 때 사용
  • GET 요청은 **request body(본문 데이터)**를 사용하지 않고,
    대신 요청 URL의 경로 또는 쿼리 파라미터에 데이터를 담아서 서버에 전달
  GET /memos/1

 

여기서 /1이 PathVariable에 해당하며, 이 id 값이 Controller 메서드의 파라미터로 들어간다.

 

2. @PathVariable vs. @RequestBody

  • @PathVariable은 URL 경로에 포함된 값을 추출할 때 사용
  • @RequestBody는 POST, PUT, PATCH 등에서 본문에 들어오는 데이터를 객체로 매핑할 때 사용
    하지만 GET 요청 바디는 거의 사용하지 않으며, 스프링에서도 기본적으로 이를 비워두도록 설계

3. 결론 및 예시

@GetMapping("/{id}")
public ResponseEntity<MemoResponseDto> findMemoById(@PathVariable Long id) {
    // 여기서 id는 URL 경로에서 받아옵니다.
    return new ResponseEntity<>(memoService.findMemoById(id), HttpStatus.OK);
}

 

  • 이 메서드는 URL의 {id} 부분(즉, /memos/1에서 1)을 받아 사용
  • 별도의 요청 바디가 필요 없으므로 @RequestBody를 사용하지 않다.

 

반면 POST/PUT/PATCH는?

@PostMapping
public ResponseEntity<MemoResponseDto> createMemo(@RequestBody MemoRequestDto dto) {
    ...
}

 

이런 경우처럼, 본문에 담긴 데이터를 자바 객체로 변환해 사용해야 할 때 @RequestBody가 필요하다.

 

정리:

  • @GetMapping("/{id}")에선 조회용으로 URL 경로의 값을 @PathVariable로 받기 때문에 @RequestBody가 필요 없다!
  • @RequestBody는 주로 데이터 생성/수정 등의 요청 시 사용. (POST, PUT, PATCH)

 

DELETE 요청도 GET 요청과 마찬가지로 보통 리소스의 ‘id’ 값 등 주요 정보를 URL 경로(PathVariable)에서 받아온다.

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteMemo(@PathVariable Long id) {
    memoService.deleteMemo(id);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
  • 위 예시에서 @PathVariable Long id를 통해 URL에서 id 값을 받아 삭제할 대상을 지정한다.
  • 별도의 요청 바디(@RequestBody)가 필요하지 않다.

 

정리

  • 대개 @DeleteMapping("/{id}")처럼 @PathVariable로만 정보를 받아 처리한다.
  • DELETE에서 @RequestBody를 쓰는 일은 드물고, 권장되도 않는다.

 

'Spring > 이론' 카테고리의 다른 글

Spring 데이터 변환 컴포넌트들  (0) 2025.06.04
Spring Layered Architecture  (0) 2025.05.09
Spring @RestController & ResponseEntity<T>에 대해  (0) 2025.05.08
Spring DTO에 대해  (0) 2025.05.08
Spring MVC 구조  (0) 2025.05.08