[스프링] ResponseEntity

June·2021년 8월 17일
1

코드숨

목록 보기
3/8

ResponseEntity란?

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

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

우선 자바에서 구현체를 살펴보자.

ResponseEntity

public class ResponseEntity<T> extends HttpEntity<T> {

	private final Object status;
	...
        <T> ResponseEntity<T> body(@Nullable T body);

RequestEntityResponseEntityHttpEntity 클래스를 상속받아 구현했다. 그래서 HttpStatus, HttpHeaders, HttpBody를 포함한다.

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

그렇다면 왜 쓰는 것일까?

지금까지는 반환 타입을 일반 객체로 해왔다. 하지만 ResponseEntity를 사용함으로서 내가 반환 값을 커스텀할 수 있다. 예를 들어 어떤 문제가 생겼을 때 서버 내부의 보안을 위해 상태 코드를 바꿔서 줄 수 있고, body에도 특정 메시지만 담아서 줄 수 있는 것이다.

https://velog.io/@injoon2019/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%8A%A4%ED%94%84%EB%A7%815-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-%EC%9E%85%EB%AC%B8-16-%EC%9E%A5-JSON-%EC%9D%91%EB%8B%B5%EA%B3%BC-%EC%9A%94%EC%B2%AD-%EC%B2%98%EB%A6%AC

사용법

ResponseEntity를 생성하는 기본 방법은 status와 body를 이용해서 상태코드와 JSON으로 변환할 객체를 지정하는 것이다.

ResponseEntity.statsu(상태코드).body(객체)

200(OK) 응답 코드와 몸체 데이터를 생성할 경우 다음과 같이 ok() 메서드를 이용해서 생성할 수 있다.

ResponseEntity.ok(member)

만약 몸체 내용이 없다면 다음과 같이 body를 지정하지 않고 build()로 바로 생성한다.

ResponseEntity.status(HttpStatus.NOT_FOUND).build()

참고해야 할 블로그

https://woowacourse.github.io/tecoble/post/2021-05-10-response-entity/

0개의 댓글