일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- JPA
- 워드프레스
- useEffect
- router
- ChatGPT
- addallattributes()
- 구글
- Thymeleaf
- 플러그인
- db
- 데이터베이스
- 리액트오류
- SEO
- Login
- set
- 인텔리제이
- @Query
- Polylang
- GET
- 구글알고리즘
- post
- @Entity
- @Repository
- 구글애널리틱스
- GA4
- HttpSession
- linkedhastset
- mergeattributes()
- @Controller
- firebase
- Today
- Total
개발천재
[Spring Boot] ResponseEntity, 유연한 HTTP 응답 처리하기 본문
ResponseEntity 이해하기
ResponseEntity<T>는 Spring Boot에서 HTTP 응답을 보다 세밀하게 조작할 수 있도록 도와주는 클래스이다. <T> 부분에 반환할 데이터 타입(String, List 등)을 지정할 수 있다.
JSON 데이터뿐만 아니라, HTTP 상태 코드, 헤더, 바디(내용) 등을 포함한 응답을 반환할 때 사용된다.
ResponseEntity 기본 사용법
ResponseEntity.status(HttpStatus status)는 응답의 HTTP 상태 코드를 설정하는 메서드이다.
이 메서드를 사용하면 200(OK), 400(Bad Request), 404(Not Found) 등 다양한 상태 코드를 응답에 지정할 수 있다.
ResponseEntity.body(T body)는 HTTP 응답 본문(Body) 에 데이터를 담는 메서드이다. 즉, 클라이언트가 받을 데이터를 설정하는 역할을 합한다. .body("Hello, World!")는 응답 본문(Body)을 설정한 것이고, 클라이언트가 /api/hello로 요청하면 "Hello, World!"를 포함한 HTTP 200 응답을 받는다.
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class ExampleController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.status(HttpStatus.OK)
.body("Hello, World!");
}
}
ResponseEntity의 장점
ResponseEntity는 Spring에서 API 응답을 보다 유연하고 명확하게 처리할 수 있도록 도와주는 객체이다. 단순히 데이터만 반환하는 것이 아니라, HTTP 상태 코드(예: 200 OK, 400 Bad Request)와 함께 응답 헤더까지 설정할 수 있어 클라이언트가 요청 결과를 쉽게 이해할 수 있다. 이를 통해 예외 처리나 오류 응답을 더 체계적으로 관리할 수 있으며, JSON이나 문자열 등 다양한 형태의 데이터를 손쉽게 반환할 수 있어 RESTful API 개발에 매우 유용하다.
HTTP 상태 코드 설정 가능
다양한 HTTP 상태 코드를 설정하여 API 응답을 관리할 수 있다.
예: 200 OK, 201 Created, 400 Bad Request, 500 Internal Server Error 등
ResponseEntity.status(HttpStatus.BAD_REQUEST).body("잘못된 요청입니다.")
@GetMapping("/status")
public ResponseEntity<String> getStatus(@RequestParam int code) {
if (code == 404) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("요청한 리소스를 찾을 수 없습니다."); // 404 Not Found
} else if (code == 500) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("서버 오류 발생"); // 500 Internal Server Error
}
return ResponseEntity.ok("정상 요청입니다."); // 200 OK
}
헤더(Header) 설정 가능
HttpHeaders 객체를 사용해 응답 헤더를 설정할 수 있다.
아래의 예시는 headers.add("Custom-Header", "HeaderValue")를 통해 Custom-Header를 추가했다.
@RestController
public class HeaderController {
@GetMapping("/headers")
public ResponseEntity<String> getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "HeaderValue");
return ResponseEntity.status(HttpStatus.OK)
.headers(headers)
.body("헤더가 포함된 응답입니다.");
}
}
JSON 데이터 반환 가능
Map<String, Object>를 사용해 JSON 형식의 데이터를 반환할 수 있다.
아래의 예시를 보면 사용자 정보가 없을 경우 404 Not Found 응답을 반환하도록 처리되어 있다.
@RestController
public class JsonResponseController {
@GetMapping("/user/{id}")
public ResponseEntity<Map<String, Object>> getUser(@PathVariable int id) {
Map<String, Object> response = new HashMap<>();
if (id == 1) {
response.put("id", 1);
response.put("name", "홍길동");
response.put("email", "hong@example.com");
return ResponseEntity.ok(response); // 200 OK
}
response.put("message", "사용자를 찾을 수 없습니다.");
return ResponseEntity.status(404).body(response); // 404 Not Found
}
}
에러 응답을 깔끔하게 관리 가능
HTTP 404 응답을 반환하면서, 에러 메시지를 포함할 수 있다.
@GetMapping("/error")
public ResponseEntity<String> errorExample() {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("요청한 데이터를 찾을 수 없습니다.");
}
예외 처리와 함께 사용하기
ResponseEntity는 예외 발생 시 일관된 응답을 제공하는 데도 유용하다.
아래의 예시는 /divide 엔드포인트에서 0으로 나누는 경우 예외를 발생시킨다. @ExceptionHandler를 이용해 예외가 발생하면 400 Bad Request 응답을 반환하도록 설정되어 있다.
@RestController
public class ExceptionController {
@GetMapping("/divide")
public ResponseEntity<Integer> divide(@RequestParam int a, @RequestParam int b) {
if (b == 0) {
throw new IllegalArgumentException("0으로 나눌 수 없습니다.");
}
return ResponseEntity.ok(a / b);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleException(IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
'개발 준비 > Spring Boot' 카테고리의 다른 글
[Spring Boot] @RestController, 효과적인 API 개발을 위한 핵심 가이드 (2) | 2025.03.04 |
---|---|
[Spring Boot] JPA Cascade 완벽 가이드 (2) | 2025.02.27 |
[Spring Boot] JPQL로 이해하는 데이터베이스 접근 방식 (0) | 2025.02.27 |
[Spring Boot] JPA 매핑 어노테이션 정리 (1) | 2025.02.27 |
[Spring Boot] JPA 영속성 컨텍스트 완벽 이해: 개념부터 실전 활용까지 (1) | 2025.02.26 |