Spring 프레임워크는 RESTful 웹 서비스를 구축하기 위한 다양한 도구와 기능을 제공합니다. 그 중 하나가 ResponseEntity입니다. ResponseEntity는 HTTP 응답을 보다 세밀하게 제어할 수 있는 방법을 제공합니다. 이를 통해 HTTP 상태 코드, 헤더, 응답 본문 등을 설정할 수 있습니다. 이 글에서는 ResponseEntity의 개념과 사용 방법을 예시 코드와 함께 설명하겠습니다.
ResponseEntity는 Spring MVC에서 클라이언트로 반환되는 HTTP 응답을 표현하는 클래스입니다. 이를 통해 다음과 같은 작업을 할 수 있습니다.
ResponseEntity.ok(): 200 OK 상태 코드를 반환합니다.ResponseEntity.status(HttpStatus status): 특정 HTTP 상태 코드를 반환합니다.ResponseEntity.badRequest(): 400 Bad Request 상태 코드를 반환합니다.ResponseEntity.notFound(): 404 Not Found 상태 코드를 반환합니다.ResponseEntity.headers(HttpHeaders headers): 특정 헤더를 설정합니다.ResponseEntity.body(Object body): 응답 본문을 설정합니다.아래는 간단한 Spring Boot 애플리케이션에서 ResponseEntity를 사용하는 예제입니다.
Spring Boot 프로젝트를 생성하고 spring-boot-starter-web 의존성을 추가합니다. Maven을 사용하는 경우 pom.xml 파일에 다음과 같이 추가합니다:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
ResponseEntity를 사용하여 HTTP 응답을 반환하는 REST 컨트롤러를 작성합니다.
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/hello")
public ResponseEntity<String> sayHello(@RequestParam(value = "name", defaultValue = "World") String name) {
return ResponseEntity.ok("Hello, " + name + "!");
}
@GetMapping("/custom-header")
public ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "CustomHeaderValue");
return ResponseEntity.status(HttpStatus.ACCEPTED)
.headers(headers)
.body("Custom header set with 202 Accepted status");
}
@GetMapping("/bad-request")
public ResponseEntity<String> badRequest() {
return ResponseEntity.badRequest().body("Bad Request Error");
}
@GetMapping("/not-found")
public ResponseEntity<String> notFound() {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
}
}
Spring Boot 애플리케이션을 실행한 후, 다양한 엔드포인트에 대해 HTTP 요청을 보내어 ResponseEntity의 동작을 확인할 수 있습니다.
/hello?name=Spring: "Hello, Spring!" 응답과 함께 200 OK 상태 코드 반환/custom-header: "Custom header set with 202 Accepted status" 응답과 함께 202 Accepted 상태 코드 및 커스텀 헤더 반환/bad-request: "Bad Request Error" 응답과 함께 400 Bad Request 상태 코드 반환/not-found: "Resource not found" 응답과 함께 404 Not Found 상태 코드 반환ResponseEntity를 사용하면 Spring 애플리케이션에서 HTTP 응답을 보다 유연하고 세밀하게 제어할 수 있습니다. 이를 통해 클라이언트에게 보다 정확한 상태 코드와 정보를 제공할 수 있으며, RESTful 서비스의 품질을 향상시킬 수 있습니다.