본문 바로가기

Spring/공부공부

[Spring / HTTP] ResponseEntity

 

[ ResponseEntity ] 

스프링 프레임워크(Spring Framework)에서 HTTP 응답을 상세하게 제어할 수 있도록 제공하는 클래스.

* HttpEntity 를 상속받아 구현된 클래스. ( HttpEntity 클래스는 HttpHeader와 HttpBody를 포함. )

package org.springframework.http;


public class ResponseEntity<T> extends HttpEntity<T> {
	
    private final HttpStatusCode status;
	
    // .....
}

=> 따라서 HTTP 응답의 body, status code, headers 등을 포함한다. 

 


* 예시 *

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class TestController {

    @PostMapping("/getInfo")
    @ResponseBody
    public ResponseEntity<List<String>> getInfo(@RequestBody TestDto testDto){

        List<String> testInfo = TestService.getInfo(testDto);
        return ResponseEntity.ok(testInfo);

//     return new ResponseEntity<>(testInfo, HttpStatus.OK);  // 명시적으로 상태 코드 설정

    }
}

=> '200 OK' 상태 코드와 함께 'testInfo'를 HTTP 응답 본문(body)에 담아 리턴.


응답 HTTP 헤더에도 정보를 추가할 수 있다. (메서드 체인)

return ResponseEntity.ok()
                     .header("Custom-Header", "Value")
                     .body(testInfo);

 


 

응답할 데이터를 담을 Message 객체 생성. 

import org.springframework.http.HttpStatus;
import lombok.Data;

@Data
public class Message<T> {
    private HttpStatus status;
    private String message;
    private T data;

    public Message(HttpStatus status, String message, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }
}

 

컨드롤러에서는 모든 정보를 담고있는 획일화된 객체를 내보내준다.

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
public class TestController {

    @GetMapping("/getInfo")
    public ResponseEntity<Message<List<String>>> getInfo() {
        List<String> values = List.of("value1", "value2", "value3");
        Message<List<String>> message = new Message<>(HttpStatus.OK, "Success", values);
        return ResponseEntity.ok().body(message);
        
//      return new ResponseEntity<>(message, message.getStatus());
    }
}