250x250
Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags more
Archives
Today
Total
관리 메뉴

개린이 개발노트

[스프링] ResponseEntity 본문

스프링Spring

[스프링] ResponseEntity

개린이9999 2022. 12. 9. 08:31
728x90

ResponseEntity란?

 

JSON 포멧을 쓸 때 즐겨쓰는 방식, 리턴되는 데이터 타입을 ↓ 이런 데이터 타입으로 만들어 주는것.

 

 

 

 

 

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

 

ResponseEntity (Spring Framework 6.0.2 API)

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

docs.spring.io

 

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

ResponseEntity

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

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

RequestEntity와 ResponseEntity는 HttpEntity 클래스를 상속받아 구현했다. 그래서 HttpStatus, HttpHeaders, HttpBody를 포함한다.

 

그렇다면 왜 쓰는 것일까?

지금까지는 반환 타입을 일반 객체로 해왔다. 하지만 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

 

[스프링] 스프링5 프로그래밍 입문 - 16 장 : JSON 응답과 요청 처리

웹 페이지에서 Ajax를 이용해서 서버 API를 호출하는 사이트가 많다. 이들 API는 웹 요청에 대한 응답으로 HTML 대신 JSON이나 XML을 이용한다. 웹 요청에도 쿼리 문자열 대신에 JOSN이나 XML을 데이터로

velog.io

사용법

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/

728x90