반응형

Spring Boot에서 ResponseEntity를 이용한 데이터 전송 방법

Spring Boot에서 서버가 클라이언트에게 데이터를 전달하는 방법에는 여러 가지가 있습니다. 그중에서도 ResponseEntity를 활용하면 HTTP 응답 상태 코드, 헤더, 그리고 응답 데이터를 모두 포함할 수 있어 더욱 유연한 응답 처리가 가능합니다. 이번 글에서는 ResponseEntity에 DTO(Data Transfer Object)를 담아 클라이언트로 전송하는 방법을 설명하고, 예제 코드를 통해 실습해 보겠습니다.


1. ResponseEntity란?

ResponseEntity는 Spring 프레임워크에서 제공하는 클래스로, HTTP 응답을 보다 세밀하게 제어할 수 있도록 도와줍니다. 기본적으로 다음과 같은 요소를 포함할 수 있습니다.

  • HTTP 상태 코드 (Status Code): 응답의 성공/실패 여부를 나타냄 (예: 200 OK, 400 Bad Request 등)
  • HTTP 헤더 (Headers): 추가적인 메타데이터를 담을 수 있음
  • 응답 본문 (Body): 클라이언트에게 전달할 데이터

DTO를 ResponseEntity에 담아 반환하면, 클라이언트는 상태 코드와 함께 구조화된 데이터를 받을 수 있습니다.


2. DTO 클래스 생성

우선, 클라이언트에게 보낼 데이터를 담을 DTO 클래스를 정의합니다.

public class UserDTO {
    private String name;
    private int age;
    public UserDTO(String name, int age) {
    	this.name = name;
    	this.age = age;
    } 

    // Getter & Setter
    public String getName() { return name; } 
    public void setName(String name) { this.name = name; } 
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; } 
}
 

3. Controller에서 ResponseEntity로 데이터 반환

이제 Spring Boot의 @RestController를 사용하여 데이터를 반환하는 엔드포인트를 만들어 봅시다.

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 UserController {
    @GetMapping("/user")
    public ResponseEntity<UserDTO> getUser(@RequestParam String name, @RequestParam int age) {
        UserDTO user = new UserDTO(name, age);
        return ResponseEntity.ok(user);
        // HTTP 200 OK + UserDTO 객체 반환 
    }
}

🔹 설명

  • @GetMapping("/user"): /user 엔드포인트로 GET 요청이 오면 getUser 메서드 실행
  • @RequestParam: 쿼리 파라미터를 받아 DTO 객체 생성
  • ResponseEntity.ok(user): HTTP 상태 코드 200(OK)와 함께 UserDTO 객체를 JSON 형식으로 반환

4. HTTP 요청 및 응답 예시

▶ 클라이언트에서 요청

GET /user?name=John&age=30
HTTP/1.1 Host: localhost:8080

▶ 서버 응답

HTTP/1.1 200 OK
Content-Type: application/json
{ "name": "John", "age": 30 }

5. HTTP 상태 코드 조정

ResponseEntity를 사용하면 상태 코드를 쉽게 변경할 수 있습니다. 예를 들어, 특정 조건에서 400 Bad Request를 반환할 수도 있습니다.

@GetMapping("/validateUser")
public ResponseEntity<?> validateUser(@RequestParam int age) {
    if (age < 0) {
	    return ResponseEntity.badRequest().body("Age cannot be negative");
    }
    UserDTO user = new UserDTO("Default Name", age);
    return ResponseEntity.ok(user);
}

 

 

▶ 잘못된 요청 예시

 
GET /validateUser?age=-5 HTTP/1.1

▶ 서버 응답

 
HTTP/1.1 400 Bad Request
Content-Type: text/plain
Age cannot be negative

6. 결론

Spring Boot에서 ResponseEntity를 활용하면 HTTP 상태 코드와 데이터를 함께 반환할 수 있어 보다 유연한 응답 처리가 가능합니다. 특히 DTO를 사용하면 데이터를 명확한 구조로 전달할 수 있어 클라이언트와의 API 통신이 원활해집니다.


📌 요약

  1. ResponseEntity는 HTTP 상태 코드, 헤더, 응답 데이터를 포함하는 클래스이다.
  2. DTO를 사용하면 데이터를 구조화하여 클라이언트에게 전달할 수 있다.
  3. ResponseEntity.ok(dto)를 사용하면 JSON 응답과 함께 HTTP 200 상태를 반환할 수 있다.
  4. ResponseEntity.badRequest() 등으로 다양한 HTTP 상태 코드도 쉽게 조정 가능하다.
반응형

+ Recent posts