[๐Ÿ’ก] @RestController์— ๊ด€ํ•˜์—ฌ..(_ _)

์„œ์€๊ฒฝยท2023๋…„ 2์›” 13์ผ
0

Spring

๋ชฉ๋ก ๋ณด๊ธฐ
41/43

๊ฐœ์ธ ํ”„๋กœ์ ํŠธ๋ฅผ ๋งŒ๋“ค์–ด๋ณด๋ฉด์„œ ๋Œ€๊ฐ•๋งŒ ์•Œ๊ณ  ์“ฐ๋Š” ๊ฒŒ ์ฐธ ๋งŽ๋‹ค๋Š” ๊ฑธ ๋Š๊ผˆ๋‹ค.
๋‚ด ์‚ฌ์ „์— ๋Œ€๊ฐ•๋งŒ ์•ˆ๋‹ค๋Š” ๊ฑด ๋ง์ด ์•ˆ๋˜์ง€ ๐Ÿ‘ฉโ€๐Ÿ’ปโŒ ์•„์ฃผ์•„์ฃผ ๊ธฐ์ดˆ์ ์ด๊ณ  ์„ธ์„ธํ•œ ๊ฒƒ๋„ ๋ชจ๋‘ ์ •๋ฆฌ ~!!
(๊ฐ ํ”Œ์  ํ”ผ๋“œ๋ฐฑ ํ•ด์ฃผ์‹  ์ „์ง์žฅ ์ฃผ์ž„๋‹˜๊ป˜ ๋ฌดํ•œ๊ฐ์‚ฌ๋ฅผ ๋“œ๋ฆฝ๋‹ˆ๋‹ค)

@RestController

@Controller + @ResponseBody ๊ฐ€ ๊ฒฐํ•ฉ๋œ ํ˜•ํƒœ์˜ ์–ด๋…ธํ…Œ์ด์…˜์ด๋‹ค. @RestController๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํด๋ž˜์Šค ํ•˜์œ„ ๋ฉ”์„œ๋“œ์— @ResponseBody ์–ด๋…ธํ…Œ์ด์…˜์„ ๋‹ฌ์•„์ฃผ์ง€ ์•Š์•„๋„ ๋ฌธ์ž์—ด์ด๋‚˜ JSON์„ ๋ฆฌํ„ดํ•  ์ˆ˜ ์žˆ๊ฒŒ๋œ๋‹ค.

    
	@ApiOperation("์ปคํ”ผ ๋ฉ”๋‰ด ๋ชฉ๋ก ์กฐํšŒ API")
    @GetMapping("")
    public List<MenuResponseDto> show() {
        List<Coffee> coffeeList = menuService.show();
        List<MenuResponseDto> response = new ArrayList<>();
        for (Coffee c : coffeeList) {
            response.add(new MenuResponseDto(c));
        }
        return response;
    }

๊ฒฐ๊ณผ๋Š” ์ด๋ ‡๊ฒŒ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ž๋™์œผ๋กœ jsonํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ๊ฑธ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

[
    {
        "id": 1,
        "coffeeName": "Americano",
        "price": 4500
    },
    {
        "id": 2,
        "coffeeName": "Cappuccino",
        "price": 5000
    },
    {
        "id": 3,
        "coffeeName": "Coldbrew",
        "price": 5500
    },
    {
        "id": 4,
        "coffeeName": "Latte",
        "price": 5000
    },
    {
        "id": 5,
        "coffeeName": "Espresso",
        "price": 3000
    }
]

@ResponseEntity

์ฒ˜์Œ์—” ์ด๋ ‡๊ฒŒ ๋ฆฌํ„ด๊ฐ’์„ ResponseEntity๋กœ ์ฃผ์—ˆ๋‹ค.
ํ•˜์ง€๋งŒ ๋‹จ์ˆœํžˆ list๋ฅผ ๋‹ด๊ธฐ๋งŒ ํ•˜์—ฌ ๋ฆฌํ„ดํ•˜๋Š” ๊ผด๋กœ ์œ„ ์†Œ์Šค์™€ ๋™์ผํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค.
@ResponseEntity๋Š” ์ƒํƒœ์ฝ”๋“œ๋ฅผ ์ „์†กํ•˜๊ณ  ์‹ถ์€ ๋ฐ์ดํ„ฐ์™€ ํ•จ๊ป˜ ๋ณด๋‚ด ์ข€ ๋” ์„ธ๋ฐ€ํ•œ ์ œ์–ด๊ฐ€ ํ•„์š”ํ•œ ๊ฒฝ์šฐ ์‚ฌ์šฉํ•œ๋‹ค. ์ด ๋ฉ”์„œ๋“œ์—์„œ๋Š” ๊ทธ๋ƒฅ ๋ฆฌ์ŠคํŠธ๋งŒ ๋ฟŒ๋ ค์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ๊ตณ์ด๊ตณ์ด์˜€๋‹ค.

ํ—ค๋”๋‚˜ HTTP ์ƒํƒœ์ฝ”๋“œ์™€ ๋ฐ์ดํ„ฐ๋ฅผ ํ•จ๊ป˜ ์—ฎ์–ด ๋ณด๋‚ผ ๋•Œ ์‚ฌ์šฉํ•˜์ž!


	@ApiOperation("์ปคํ”ผ ๋ฉ”๋‰ด ๋ชฉ๋ก ์กฐํšŒ API")
    @GetMapping("")
    public ResponseEntity show() {
        List<Coffee> coffeeList = menuService.show();
        List<MenuResponseDto> response = new ArrayList<>();
        for (Coffee c : coffeeList) {
            response.add(new MenuResponseDto(c));
        }
        return ResponseEntity.ok(response);
    }

0๊ฐœ์˜ ๋Œ“๊ธ€