Bibi's DevLog ๐Ÿค“๐ŸŽ

[Spring] ResponseEntity, @RestController, @RequestBody, @ResponseBody ๋ณธ๋ฌธ

๐Ÿ–ฅ BE ๋ฐฑ์—”๋“œ/Spring ์Šคํ”„๋ง

[Spring] ResponseEntity, @RestController, @RequestBody, @ResponseBody

๋น„๋น„ bibi 2021. 4. 30. 19:59

ResponseEntity, @RestController, @RequestBody, @ResponseBody

// UPDATE
@PutMapping("/cards/{id}")
public ResponseEntity editCards(@PathVariable Long id, @RequestBody CardDto newCardDto) {
    cardService.edit(id, newCardDto);
    return new ResponseEntity<>("SUCCESS", HttpStatus.OK);
}
  • ResponseEntity
    • HttpEntity : HTTP ์š”์ฒญ ๋˜๋Š” ์‘๋‹ต์— ํ•ด๋‹นํ•˜๋Š” HTTP Header์™€ HTTP Body๋ฅผ ํฌํ•จํ•˜๋Š” Spring FrameWork์˜ ํด๋ž˜์Šค์ด๋‹ค.
    • ์ด๋Ÿฌํ•œ HttpEntity๋ฅผ ์ƒ์†๋ฐ›์•„ ๊ตฌํ˜„ํ•œ ํด๋ž˜์Šค๊ฐ€ RequestEntity,ResponseEntity์ด๋‹ค.
    • ResponseEntity : ์‚ฌ์šฉ์ž์˜ HttpRequest์— ๋Œ€ํ•œ ์‘๋‹ต ๋ฐ์ดํ„ฐ๋ฅผ ํฌํ•จํ•˜๋Š” ํด๋ž˜์Šค.
      • HttpStatus, HttpHeaders, HttpBody๋ฅผ ํฌํ•จํ•œ๋‹ค.
    • ์™œ ์“ฐ๋Š”๊ฐ€?
      • ์ผ๋ฐ˜์ ์ธ ์ฝ”๋“œ์˜ ๋ฐ˜ํ™˜๊ฐ’์€ '๊ฐ’'๋งŒ์œผ๋กœ ์ถฉ๋ถ„ํ•˜์ง€๋งŒ, API์˜ ๋ฐ˜ํ™˜ ๋ฆฌ์†Œ์Šค๋Š” ๊ฐ’๋งŒ์œผ๋กœ ์ถฉ๋ถ„ํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ.
      • ์ƒํƒœ์ฝ”๋“œ, ์‘๋‹ต ๋ฉ”์‹œ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • @RestController ์ฐธ๊ณ 
    • ๊ทธ๋ƒฅ @Controller์™€์˜ ์ฐจ์ด? = HTTP ResponseBody๊ฐ€ ์ƒ์„ฑ๋˜๋Š” ๋ฐฉ์‹์ด ๋‹ค๋ฅด๋‹ค.
    • @Controller : ์ฃผ๋กœ View๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•œ๋‹ค.
      • View ๋ฐ˜ํ™˜์„ ์œ„ํ•ด ๋‚ด๋ถ€์ ์œผ๋กœ ViewResolver๊ฐ€ ๋™์ž‘ํ•œ๋‹ค.
    • @RestController : JSONํ˜•ํƒœ๋กœ ๊ฐ์ฒด ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•œ๋‹ค.
      • @ResponseBody์–ด๋…ธํ…Œ์ด์…˜์„ ํ™œ์šฉํ•ด Controller๊ฐ€ JSONํ˜•ํƒœ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
      • JSON ๋ฐ์ดํ„ฐ ๋ฐ˜ํ™˜์„ ์œ„ํ•ด ๋‚ด๋ถ€์ ์œผ๋กœ HttpMessageConverter๊ฐ€ ๋™์ž‘ํ•œ๋‹ค.
      • ๋ฐ˜ํ™˜ํ•  ๋ฐ์ดํ„ฐ์— ๋”ฐ๋ผ ์‚ฌ์šฉ๋˜๋Š” Converter๊ฐ€ ๋‹ฌ๋ผ์ง„๋‹ค.
  • @RequestBody์™€ @ResponseBody. ์ฐธ๊ณ 
    • ์Šคํ”„๋งMVC์—์„œ, ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ „์†กํ•œ ๋ฐ์ดํ„ฐ(JSON๋“ฑ)๋ฅผ ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ์ž๋ฐ” ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•ด ๋ฐ›๊ณ  & ์ž๋ฐ” ๊ฐ์ฒด๋ฅผ ๋ฐ์ดํ„ฐ(JSON ๋“ฑ)๋กœ ๋ณ€ํ™˜ํ•ด ์ „์†กํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•จ.
    • @RequestBody
      • HTTP Request์˜ Body๋ฅผ ์ž๋ฐ” ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•  ๋•Œ ์‚ฌ์šฉ
    • @ResponseBody
      • ์ž๋ฐ” ๊ฐ์ฒด๋ฅผ HTTP Response์˜ Body๋กœ ๋ณ€ํ™˜ํ•  ๋•Œ ์‚ฌ์šฉ