본문 바로가기

웹 개발/스프링

[스프링 부트 심화] HttpEntity, ResponseEntity, HttpStatus

0. HttpEntity란

HttpEntity는 헤더와 비디로 이루어진 HTTP response, requesst 엔터티를 대표한다. 

Java.lang.Object <- HttpEntity <- RequestEntity, ResponseEntity

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpEntity.html#field.summary

 

HttpEntity (Spring Framework 6.0.8 API)

hasBody public boolean hasBody() Indicates whether this entity has a body.

docs.spring.io

public class HttpEntity<T> {
    public static final HttpEntity<?> EMPTY = new HttpEntity();
    private final HttpHeaders headers;
    private final T body;
    ...
}

ResponseEntity와 RequestEntity는 HttpEntity를 구현한다. HttpEntity는 헤더와 바디 필드를 가지고 있다. 따라서 ResponseEntity는 사용자의 요청에 응답할 데이터를 포함시킨 클래스로서 상속 받은 헤더와 바디 필드를 가지고 있고 또한 HttpStatus 필드를 지닌다. 

 

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

 

ResponseEntity (Spring Framework 6.0.8 API)

Create a ResponseEntity with a body, headers, and a raw status code.

docs.spring.io

 

1. ResponseEntity란

ResponseEntity 설명 : 

Extension of HttpEntity that adds an HttpStatusCode status code. Used in RestTemplate as well as in @Controller methods.

 

Spring MVC의 @Controller 어노테이션과 함께 사용될 경우 다음과 같이 사용할 수 있다. 

 @RequestMapping("/handle")
 public ResponseEntity<String> handle() {
   URI location = ...;
   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.setLocation(location);
   responseHeaders.set("MyResponseHeader", "MyValue");
   return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
 }

혹은 builder 패턴을 활용하여 다음과 같이 사용할 수 있다.

 @RequestMapping("/handle")
 public ResponseEntity<String> handle() {
   URI location = ...;
   return ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body("Hello World");
 }

 

 

2. HttpStatus란

HTTP status code의 열거형 객체. HTTP status code를 series()를 통해 가져올 수 있다.

용례 : 

HttpStatus.OK
HttpStatus.NOT_FOUND

 

3. 왜 응답에 헤더를 추가하거나 바디를 재정의하는 등 ResponseEntity를 사용할까?

 

REST API는 별도의 뷰를 제공하지 않고 클라이언트와 서버 간 필요한 정보들을 제공해야 합니다. 이 때, ResponseEntity를 사용해 적절한 상태코드, 헤더, 본문을 생성해서 클라이언트로 적절히 전달할 수 있습니다.

 

만약 결과 데이터가 예외 처리된 경우 전송해야 하고 전송 받아야 하는 데이터를 보다 세밀하게 제어할 수 있습니다. 

 

ResponseEntity는 즉 개발자가 직접 결과 데이터와 HTTP 상태 코드를 직접 제어할 수 있는 클래스입니다. 

 

핵심은 ErrorResponse 객체를 통한 에러가 담긴 응답 메시지의 통일성 있는 구현이다. 아직은 무슨 말인지 몰라 더 학습을 이어가겠다.

https://cheese10yun.github.io/spring-guide-exception/

 

Spring Guide - Exception 전략 - Yun Blog | 기술 블로그

Spring Guide - Exception 전략 - Yun Blog | 기술 블로그

cheese10yun.github.io