Spring
[Spring] ResponseEntity 이란?
kyungeeee
2022. 12. 22. 22:47

- ResponseEntity는 HttpEntity를 상속받는다.
- 데이터의 결과 값과 HTTP 상태 코드를 개발자가 제어할 수 있는 클래스이다.
- 클라이언트의 요청에 대한 응답 데이터가 포함되어있다.
- ResponseEntity에는 HttpStatus, HttpHeaders, HttpBody 를 포함한다.
- 상태코드, 헤더값, 결과값 등의 데이터를 프론트엔드에게 넘겨줄 수 있고, 에러코드도 자세히 설정해서 전달할 수 있다.
📌 ResponseEntity 구조
- HttpEntity에서 상속받은 status, headers, body를 매개변수로 받는다.
- status : 상태 코드를 제어하여 넘김 http 상태 코드
- headers : 요청/응답에 대한 요구사항 포함
- body : 결과에 대한 값 포함
- body와 header 부분은 'null'이 들어올 수 있음
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
|
public class ResponseEntity<T> extends HttpEntity<T> {
private final Object status;
public ResponseEntity(HttpStatus status) {
this(null, null, status);
}
public ResponseEntity(@Nullable T body, HttpStatus status) {
this(body, null, status);
}
public ResponseEntity(MultiValueMap<String, String> headers, HttpStatus status) {
this(null, headers, status);
}
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
this(body, headers, (Object) status);
}
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, int rawStatus) {
this(body, headers, (Object) rawStatus);
}
private ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, Object status) {
super(body, headers);
Assert.notNull(status, "HttpStatus must not be null");
this.status = status;
}
|
cs |
📌 ResponseEntity 사용법
- ResponseEntity<dto> 로 작성하여 응답데이터를 넘겨 준다.
- status([상태코드])로 상태코드를 변경하여 넘겨 줄 수도 있다.
- body([넘겨줄객체]) 객체 데이터를 담아 body로 결과 값을 넘겨줄 수 있다.
1
2
3
4
5
6
7
|
// Controller
@GetMapping("/{id}")
public ResponseEntity<ArticleResponse> get(@PathVariable Long id) {
ArticleResponse articleResponse = articleService.getArticleById(id);
return ResponseEntity.ok().body(articleResponse);
}
|
cs |
1
2
3
4
5
6
7
8
|
// Response
@Getter
@AllArgsConstructor
public class ArticleResponse {
private Long id;
private String title;
private String content;
}
|
cs |

👇 아래와 같이 상태코드를 수정하여 전달해 줄 수도 있음
1
2
3
4
5
6
|
@GetMapping("/{id}")
public ResponseEntity<ArticleResponse> get(@PathVariable Long id) {
ArticleResponse articleResponse = articleService.getArticleById(id);
return ResponseEntity.status(333).body(articleResponse);
}
|
cs |
