๋ฐฑ์—”๋“œ(Back-End) ๊ฐœ๋ฐœ/SpringBoot

[SpringBoot] 2.3_API (@ResponseBody)

rabo93 2025. 2. 25. 14:06
  • @ResponseBody ๋ฌธ์ž ๋ฐ˜ํ™˜
package hello.hello_spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.service.annotation.GetExchange;

@Controller
public class HelloController {
	
    @GetMapping("hello-string")
    @ResponseBody // Http ํ†ต์‹  ํ”„๋กœํ† ์ฝœ์˜ body๋ถ€์— ๋‚ด๊ฐ€ ์ง์ ‘ ๋„ฃ์–ด์ฃผ๊ฒ ๋‹ค๋Š” ๋œป
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name; // viewํŽ˜์ด์ง€๊ฐ€ ์•„๋‹Œ "hello string" ๋ฌธ์ž ๊ทธ๋Œ€๋กœ ๋„˜์–ด๊ฐ
    }
    
    
    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        return hello; //JSON๋ฐฉ์‹์œผ๋กœ ๊ฐ์ฒด ๋ฐ˜ํ™˜
        
    }
    static class Hello {
        private String name;

        //getter, setter ๋‹จ์ถ•ํ‚ค : alt + insertํ‚ค
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

}

 

@ResponseBody๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ทฐ ๋ฆฌ์กธ๋ฒ„๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Œ

๋Œ€์‹ ์— HTTP BODY๋ถ€์— ๋ฌธ์ž ๋‚ด์šฉ์„ ์ง์ ‘ ๋ฐ˜ํ™˜


 

@ResponseBody๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๊ฐ์ฒด๊ฐ€ JSON์œผ๋กœ ๋ณ€ํ™˜๋จ

 

 

@ResponseBody๋ฅผ ์‚ฌ์šฉ

- HTTP์˜ BODY์— ๋ฌธ์ž ๋‚ด์šฉ์„ ์ง์ ‘ ๋ฐ˜ํ™˜

- 'ViewResolver' ๋Œ€์‹ ์— 'HTTPMessageConverter'๊ฐ€ ๋™์ž‘

- ๊ธฐ๋ณธ ๋ฌธ์ž์ฒ˜๋ฆฌ : 'StringHttpMessageConverter'

- ๊ธฐ๋ณธ ๊ฐ์ฒด์ฒ˜๋ฆฌ : 'MappingJackson2HttpMessageConverter'