Home > Spring > ๐Ÿƒ[Spring] API.

๐Ÿƒ[Spring] API.
Spring Framework

๐Ÿƒ[Spring] API.

'@ResponseBody ๋ฌธ์ž ๋ฐ˜ํ™˜'

@Controller
public class HelloController {

    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name;
    }
}
  • '@ResponseBody' ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ทฐ ๋ฆฌ์กธ๋ฒ„('viewResolver')๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
    • ๋Œ€์‹ ์— HTTP์™€ BODY์— ๋ฌธ์ž ๋‚ด์šฉ์„ ์ง์ ‘ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.(HTML BODY TAG๋ฅผ ๋งํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹™๋‹ˆ๋‹ค.)
  • ์‹คํ–‰
    • http://localhost:8080/hello-string?name=spring

'@ResponseBody ๊ฐ์ฒด ๋ฐ˜ํ™˜'

@Controller
public class HelloController {
    
    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        return hello;
    }

    static class Hello {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
  • ์‹คํ–‰
    • http://localhost:8080/hello-api?name=spring

'@ResponseBody ์‚ฌ์šฉ ์›๋ฆฌ'

  • '@ResponseBody' ๋ฅผ ์‚ฌ์šฉ
    • HTTP์˜ BODY์— ๋ฌธ์ž ๋‚ด์šฉ์„ ์ง์ ‘ ๋ฐ˜ํ™˜
    • 'viewResolver' ๋Œ€์‹ ์— 'HttpMessageConverter' ๊ฐ€ ๋™์ž‘
    • ๊ธฐ๋ณธ ๋ฌธ์ž์ฒ˜๋ฆฌ: 'StringHttpMessageConverter'
    • ๊ธฐ๋ณธ ๊ฐ์ฒด์ฒ˜๋ฆฌ: 'MappingJackson2HttpMessageConverter'
    • byte ์ฒ˜๋ฆฌ ๋“ฑ๋“ฑ ๊ธฐํƒ€ ์—ฌ๋Ÿฌ 'HttpMessageConverter' ๊ฐ€ ๊ธฐ๋ณธ์œผ๋กœ ๋“ฑ๋ก๋˜์–ด ์žˆ์Œ.

๐Ÿ™‹โ€โ™‚๏ธ ์ฐธ๊ณ : ** ํด๋ผ์ด์–ธํŠธ์˜ HTTP Accept ํ—ค๋”์™€ ์„œ๋ฒ„์˜ ์ปจํŠธ๋กค๋Ÿฌ ๋ฐ˜ํ™˜ ํƒ€์ž… ์ •๋ณด ๋‘˜์„ ์กฐํ•ฉํ•ด์„œ
**'HttpMessageConverter'
๊ฐ€ ์„ ํƒ๋œ๋‹ค.