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'
κ°€ μ„ νƒλœλ‹€.