[Spring] ResponseEntity
๐ ResponseEntity
๐ฝ ๊ฐ์
`Spring Framework`์์ ์ ๊ณตํ๋ Class ์ค `HttpEntity`๋ผ๋ Class๊ฐ ์กด์ฌํ๋ ๊ฒ์ด์์.
์ด ์น๊ตฌ๋ `HTTP Request ๋๋ Response`์ ํด๋น ํ๋ `HttpHeader`์ `HttpBody`๋ฅผ ํฌํจํ๋ Class์ธ ๊ฒ์ด์์.
public class HttpEntity<T> {
private final HttpHeaders headers;
@Nullable
private final T body;
}
public class RequestEntity<T> extends HttpEntity<T>
public class ResponseEntity<T> extends HttpEntity<T>
`HttpEntity` Class๋ฅผ ์์ ๋ฐ์ ๊ตฌํํ Class๊ฐ ๋ฐ๋ก `RequestEntity`, `ResponseEntity` Class์ธ ๊ฒ์ด์์. `ResponseEntity`๋ ์ด์ฉ์์ `HttpRequest`์ ๋ํ ์๋ต Data๋ฅผ ํฌํจํ๋ Class์ธ ๊ฒ์ด์์.
๋ฐ๋ผ์ `HttpStatus`, `HttpHeaders`, `HttpBody`๊ฐ ํฌํจ๋๋ ์น๊ตฌ์ธ ๊ฒ์ด์์.
`ResponseEntity`์ ์์ฑ์๋ฅผ ์ดํด๋ณด๋ฉด `this()`๋ฅผ ํตํด ๋งค๊ฐ๋ณ์๊ฐ 3๊ฐ์ธ ์์ฑ์๋ฅผ ํธ์ถํ๋๋ฐ, ์ด๋ฅผ ํตํด ์๋ Code ์์์์ ๋ณด๋ฏ ๋งค๊ฐ ๋ณ์๊ฐ 3๊ฐ์ธ ์์ฑ์๋ก ๊ฐ๋๋ก ์๋ํ๋ ๊ฒ์ด์์.
public ResponseEntity(HttpStatus status) {
this(null, null, status);
}
public ResponseEntity(@Nullable T body, HttpStatus status) {
this(body, null, status);
}
์๋ฅผ ๋ค์ด ์ข ๋ ์ ๋ฆฌ๋ฅผ ํด ๋ณผ๊ฒ์!
์์ ์ฝ๋
@RestController
public class SampleController {
@GetMapping("users")
public ResponseEntity getAllUsers() {
return new ResponseEntity(HttpStatus.OK);
}
}
๊ฒฐ๊ณผ
์์ Code๋ก Postmans์ ํตํด Request๋ฅผ ๋์ง๋ฉด Http Status Code๊ฐ 200์ผ๋ก ๋์์ค๋ ๊ฒ์ ๋ณผ ์ ์๋ ๊ฒ์ด์์.
์ด ์น๊ตฌ๋ Http Status Code, Http Headers, ResponseData๋ฅผ ๋ด๋ ์์ฑ์๋ ์กด์ฌํ๋ ๊ฒ์ด์์.
public class ResponseEntity<T> extends HttpEntity<T> {
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
super(body, headers);
Assert.notNull(status, "HttpStatus must not be null");
this.status = status;
}
}