교육/IT

Springboot - ResponseEntity

리치라이프 연구소 2024. 4. 20. 13:02
반응형

ResponseEntity - HTTP 요청(Request) 또는 응답(Response)에 해당하는 HttpHeader와 HttpBody를 포함하는 클래스이다.  HttpStatus, HttpHeaders, HttpBody를 포함

 

http header에는 (요청/응답)에 대한 요구사항이 http body에는 그 내용이 적혀있고,
Response header 에는 웹서버가 웹브라우저에 응답하는 메시지가 들어있고,

Reponse body에 데이터 값이 들어가있다고 합니다.

 

 

Response Entity의 생성자를 보면, status를 넣고 Response Entity를 만들면 결국 매개변수가 3개인 생성자를 호출해낸다.

public ResponseEntity(HttpStatus status) {
	this(null, null, status);
}
public ResponseEntity(@Nullable T body, HttpStatus status) {
	this(body, null, status);
}

 

작성예시

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/api/data")
    public ResponseEntity<MyData> getData() {
        // 데이터를 가져오는 로직
        MyData data = fetchDataFromDatabase(); // 데이터베이스에서 데이터 가져오는 예시

        if (data != null) {
            // 데이터를 정상적으로 가져온 경우 200 OK 응답 반환
            return ResponseEntity.ok(data);
        } else {
            // 데이터가 없는 경우 404 Not Found 응답 반환
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    // MyData 클래스는 데이터를 나타내는 모델 클래스입니다.
    private MyData fetchDataFromDatabase() {
        // 실제 데이터베이스에서 데이터를 가져와서 반환하는 로직
        return null; // 예시로 null 반환
    }
}

반응형