[Spring] ResponseEntity

2022. 3. 28. 08:00ใ†Back-End ์ž‘์—…์‹ค/Spring Framework

728x90
๋ฐ˜์‘ํ˜•

 

๐Ÿš€ 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;
	}
}

 

 

 

 

 

 

 

728x90
๋ฐ˜์‘ํ˜•