ResponseEntity는 무엇인가?

· 유창연 · 3 min read

Spring의 ResponseEntity 개념과 사용 이유를 알아봅니다. HTTP 상태 코드를 세밀하게 제어할 수 있는 응답 방식을 설명합니다.

Spring의 ResponseEntity 개념과 사용 이유를 알아봅니다. HTTP 상태 코드를 세밀하게 제어할 수 있는 응답 방식을 설명합니다.

ResponseEntity는 무엇인가?

개발하면서 모든 응답은 ResponseEntity를 사용하고 있다.

ResponseEntity는 무엇이며 어떻게 사용하는 것일까?

ResponseEntity는 HttpEntity를 상속받고 있다.

때문에 ResponseEntity는 HTTP header, body에 상태(status)를 함께 반환할 수 있다.

여기서 한가지 궁금한 것이 생겼는데

ResponseEntity를 사용하지 않고 그냥 객체를 반환하면 @ResponseBody 어노테이션에서 자동으로 HttpStatus를 생성해주는 것일까?

궁금증을 해결하기 위해서 자료를 찾아보다가 알게 된 것은 MessageConverter이다.

Spring 프레임워크에서 기본으로 제공하는 인터페이스이고 @RequestBody, @ResponseBody가 붙은 곳에서 객체를 HttpMessage로 자동으로 변환해준다.

이것에 대한 내용은 따로 다뤄보려고 한다.

Json 형태로 변환이 필요하다면 MappingJacksonHttpMessageConverter가 자바 오브젝트와 Json문서 사이에서 자동으로 변환해준다.

@ResponseBody를 붙이면 알맞은 HttpMessageConter가 동작해서 header, body, status를 만들어주는 것 같다.

**@ResponseStatus(HttpStatus.OK)**를 사용해서 직접 상태를 만들어 줄 수도 있다.

처음으로 돌아와서 ResponseEntity는 객체와 status를 함께 보내줄 수 있기 때문에 @ResponseStatus를 사용하지 않아도 되고 메소드 별로 다른 status를 반환할 수 있기 때문에 조금 더 세밀하게 상태를 전송해야 할때 사용하면 좋을 것 같다.

[참고]

https://devlog-wjdrbs96.tistory.com/182

[[Spring Boot] ResponseEntity란 무엇인가?

먼저 REST API가 무엇인지는 아래 블로그를 먼저 잘 읽어보자. https://meetup.toast.com/posts/92 REST API 제대로 알고 사용하기 : TOAST Meetup REST API 제대로 알고 사용하기 meetup.toast.com 1. ResponseEn..

devlog-wjdrbs96.tistory.com](https://devlog-wjdrbs96.tistory.com/182) https://a1010100z.tistory.com/106

[[Spring] ResponseEntity는 왜 쓰는 것이며 어떻게 쓰는걸까?

기존 내 개인 프로젝트 코드의 RestController 반환값은 모두 Object 타입이었다. 하지만, 일반적인 API는 반환하는 리소스에 Value만 있지 않다는 것을 모두 알고 있을 것이다. 당장 생각나는 것으로는

a1010100z.tistory.com](https://a1010100z.tistory.com/106) https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

[ResponseEntity (Spring Framework 5.3.8 API)

Extension of HttpEntity that adds an HttpStatus status code. Used in RestTemplate as well as in @Controller methods. In RestTemplate, this class is returned by getForEntity() and exchange(): ResponseEntity entity = template.getForEntity(“https://example.co

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

공유:

댓글

Back to Blog

관련 게시글

View All Posts »