ResponseEntity란?
ResponseEntity는 Spring Framework에서 HTTP 응답 전체를 커스터마이징할 수 있게 해주는 클래스입니다.
@RestController나 @Controller에서 일반적으로 메서드 반환 타입으로 사용되며, HTTP 상태 코드, 헤더, 바디를 원하는 대로 제어해서 응답을 반환할 수 있습니다.
왜 쓰는가? (주요 목적)
- HTTP 상태 코드 커스터마이징
- 기본적으로 @RestController에서는 객체 반환 시 항상 200 OK로 나가지만, 상황에 맞게 404, 201, 400 등 다양한 상태 코드로 직접 제어하고 싶을 때 사용해요.
- 헤더 직접 지정
- 응답에 Location, Set-Cookie, Cache-Control 같은 커스텀 헤더를 추가하거나 수정할 수 있어요.
- 응답 바디 직접 지정
- 응답 바디에 원하는 DTO, 메시지, 에러 응답 등을 자유롭게 포함할 수 있어요.
주요 사용 형태 (코드 중심)
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.ok("Hello World"); // 200 OK + Body
}
@PostMapping("/create")
public ResponseEntity<UserResponse> createUser(@RequestBody UserRequest req) {
UserResponse res = userService.create(req);
return ResponseEntity
.status(HttpStatus.CREATED) // 201 Created
.body(res);
}
@DeleteMapping("/delete/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build(); // 204 No Content (Body 없음)
}
@GetMapping("/custom-header")
public ResponseEntity<String> withHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("X-Custom-Header", "Test");
return new ResponseEntity<>("OK with Header", headers, HttpStatus.OK);
}
실무에서 가장 많이 쓰는 패턴
return ResponseEntity.ok(dto); // 200 OK + 바디
return ResponseEntity.status(HttpStatus.CREATED).body(dto); // 201 Created
return ResponseEntity.noContent().build(); // 204 No Content
return ResponseEntity.badRequest().body(errorDto); // 400 Bad Request
상황 코드
| 정상 처리 (200) | ResponseEntity.ok(body) |
| 생성 완료 (201) | ResponseEntity.status(HttpStatus.CREATED).body(body) |
| 삭제 완료 (204) | ResponseEntity.noContent().build() |
| 클라이언트 오류 (400) | ResponseEntity.badRequest().body(error) |
| 서버 오류 (500) | ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error) |
참고
- ResponseEntity는 응답을 세밀하게 제어하고 싶을 때만 쓰는 것이 좋고, 단순 CRUD API는 @RestController + DTO 반환으로도 충분한 경우가 많습니다.
- 하지만 에러 처리, 인증 실패, 생성/삭제 응답 시에는 실무에서 거의 필수적으로 ResponseEntity를 씁니다.
'Java > Spring Boot' 카테고리의 다른 글
| Getter/Setter 사용 기준 (0) | 2025.05.31 |
|---|---|
| Swagger와 API 명세 (1) | 2025.03.31 |
| Spring Boot Test 관련 (JUnit, Mockito, AssertJ,Spring Boot Test, Testcontainers ) (0) | 2025.03.31 |
| Optional<T> (0) | 2025.03.31 |
| JPQL과 QueryDSL (0) | 2025.03.31 |