ResponseEntity<T>
란? 🚀ResponseEntity<T>
개요ResponseEntity<T>
는 Spring Framework에서 HTTP 응답을 생성하고 관리하기 위한 클래스입니다.
HTTP 상태 코드, 헤더, 바디를 포함한 응답을 구성할 수 있도록 제공됩니다.
✅ Spring의 @RestController
에서 API 응답을 반환할 때 사용
✅ HTTP 응답 상태 코드(HttpStatus
), 헤더(HttpHeaders
), 바디(T
) 포함 가능
✅ REST API에서 클라이언트에게 적절한 응답을 반환하는 데 유용
📌 ResponseEntity<T>
를 사용하면 HTTP 응답을 세밀하게 제어할 수 있음!
ResponseEntity<T>
의 주요 필드public class ResponseEntity<T> extends HttpEntity<T> {
private final HttpStatusCode status; // HTTP 상태 코드
}
ResponseEntity<T>
의 주요 구성 요소1️⃣ HTTP 상태 코드 (HttpStatusCode
)
HttpStatus.OK (200)
, HttpStatus.NOT_FOUND (404)
등 2️⃣ HTTP 헤더 (HttpHeaders
)
Content-Type
, Cache-Control
, Location
등 설정 가능 3️⃣ 바디 (T
)
📌 HttpEntity<T>
를 확장하여 응답을 더 세부적으로 설정 가능!
ResponseEntity<T>
사용 예제ResponseEntity
사용 (HTTP 상태 코드 포함)import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExampleController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello, World!", HttpStatus.OK);
}
}
📌 설명
ResponseEntity<>("Hello, World!", HttpStatus.OK)
→ 응답 본문 "Hello, World!"
+ 상태 코드 200 OK
반환 200 OK
상태 코드와 함께 응답을 받게 됨 ResponseEntity.ok()
사용 (간결한 코드)@GetMapping("/greet")
public ResponseEntity<String> greet() {
return ResponseEntity.ok("Hello, Spring!");
}
📌 설명
ResponseEntity.ok("Hello, Spring!")
→ 응답 본문 "Hello, Spring!"
+ 200 OK
ResponseEntity.notFound()
사용 (404 응답)@GetMapping("/user/{id}")
public ResponseEntity<String> getUser(@PathVariable int id) {
if (id == 1) {
return ResponseEntity.ok("User Found");
} else {
return ResponseEntity.notFound().build(); // 404 Not Found
}
}
📌 설명
notFound().build()
→ HTTP 404 Not Found
상태 코드 반환 ResponseEntity
로 JSON 응답 반환@GetMapping("/json")
public ResponseEntity<User> getUser() {
User user = new User(1, "Alice");
return ResponseEntity.ok(user);
}
static class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
// Getter & Setter
}
📌 설명
ResponseEntity.ok(user)
→ JSON 형태로 객체 반환 {"id":1, "name":"Alice"}
형태의 JSON 응답을 받음 ResponseEntity
로 헤더 설정@GetMapping("/custom-header")
public ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "HelloHeader")
.body("Header included!");
}
📌 설명
header("Custom-Header", "HelloHeader")
→ 응답 헤더에 사용자 정의 값 추가 "Custom-Header": "HelloHeader"
를 확인 가능 ResponseEntity
로 201 Created
응답 반환@PostMapping("/create")
public ResponseEntity<String> createUser(@RequestBody User user) {
URI location = URI.create("/users/" + user.getId()); // 생성된 리소스 경로
return ResponseEntity.created(location).body("User Created!");
}
📌 설명
ResponseEntity.created(location).body("User Created!")
→ 201 Created
+ Location
헤더 포함 ResponseEntity<T>
의 주요 정적 메서드메서드 | 설명 |
---|---|
ok(T body) | HTTP 200 OK 응답 반환 |
created(URI location) | HTTP 201 Created 응답 반환 |
accepted() | HTTP 202 Accepted 응답 반환 |
noContent() | HTTP 204 No Content 응답 반환 |
badRequest() | HTTP 400 Bad Request 응답 반환 |
notFound() | HTTP 404 Not Found 응답 반환 |
unprocessableEntity() | HTTP 422 Unprocessable Entity 응답 반환 |
internalServerError() | HTTP 500 Internal Server Error 응답 반환 |
📌 정적 메서드를 사용하면 더 가독성이 좋은 코드 작성 가능!
ResponseEntity<T>
vs @ResponseBody
차이비교 항목 | ResponseEntity<T> | @ResponseBody |
---|---|---|
응답 데이터 포함 여부 | ✅ 가능 (Body 포함) | ✅ 가능 |
HTTP 상태 코드 설정 | ✅ 가능 (HttpStatus 지정 가능) | ❌ 항상 200 OK |
HTTP 헤더 설정 | ✅ 가능 (HttpHeaders 설정 가능) | ❌ 불가능 |
사용 방식 | 명시적(ResponseEntity.ok() , badRequest() ) | 암묵적(기본적으로 200 OK ) |
추천 사용 사례 | 다양한 HTTP 상태 코드 & 헤더 설정이 필요할 때 | 단순한 JSON 응답 반환 시 |
📌 API 응답의 상태 코드 & 헤더를 직접 설정해야 할 경우 → ResponseEntity<T>
사용!
✅ ResponseEntity<T>
는 Spring에서 HTTP 응답을 제어하는 강력한 클래스
✅ 상태 코드(HttpStatus
), 헤더(HttpHeaders
), 바디(T
)를 포함하여 응답 가능
✅ REST API 개발에서 다양한 HTTP 응답을 반환할 때 매우 유용함
✅ 정적 메서드 (ok()
, notFound()
, created()
)를 활용하면 더 가독성 높은 코드 작성 가능
추가 학습 자료