Back-end/Spring

ResponseEntity 클래스

yujin0517 2023. 10. 17. 15:28

ResponseEntity

ResponseEntity는 다양한 생성자와 메서드를 가지고 있어 다양한 종류의 응답을 처리할 수 있다.

예를 들어, 'ResponseCntity.ok(body)는 HTTP 상태 코드를 200으로 설정하고, 응답 본문에 body를 설정하는 메서드이다.

@RestController
public class MyController {

    @GetMapping("/getSomething")
    public ResponseEntity<String> getSomething() {
        String responseString = "This is the response body";
        return ResponseEntity.ok(responseString);
    }
}

위의 코드에서 getSomething 메서드는 ResponseEntity<String> 을 반환하고 이는 HTTP 응답을 나타낸다. 이 경우 응답 본문은 문자열 "This is the response body"가 된다.

ResponseEntity를 사용하면 응답의 상태 코드, 헤더 등을 세밀하게 제어할 수 있어서 다양한 상황에서 유연하게 사용할 수 있다.