API를 활용한 String, Json 리턴

정태경·2022년 7월 17일
0

Spring 다뤄보기

목록 보기
4/4
post-thumbnail

API 활용하기

기존에 정적 페이지와 템플릿 엔진을 활용한 동적 페이지 반환하는 방법에 대해 알아보았었는데, 이번엔 API를 통한 String, Json 객체 반환하는 방법에 대해 알아보자.

@ResponseBody 활용

컨트롤러에 @ResponseBody 어노테이션을 붙이면 HTTP의 BODY에 문자 내용을 직접 반환하거나, 객체를 반환할 수 있다.

HTTP의 BODY에 String 리턴

아래 샘플 코드는 http://localhost/hello-string?{key}={value} 로 들어오는 요청을 처리하는 메서드이다. @ResponseBody 어노테이션이 붙어 있고 String을 반환하고 있다.

    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name;

실행 결과

HTTP의 BODY에 Json 리턴

아래 샘플 코드는 http://localhost/hello-api?{key}={value} 로 들어오는 요청을 처리하는 메서드이다. Hello라는 클래스의 인스턴스를 활용하고 있으며, hello라는 객체를 반환하고 있다.

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

    public static class Hello {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

실행 결과

동작 원리

  1. http://localhost/hello-api?{key}={value} 요청이 들어온다.
  2. Spring 내장 톰캣 서버에서 스프링 컨테이너의 컨트롤러로 던진다.
  3. @ResponseBody 어노테이션이 붙어 있다면 View Resolver 대신에 HttpMessageConverter 가 동작한다.
    3-1. 기본 문자 처리 : StringHttpMessageConverter
    3-2. 기본 객체 처리 : MappingJackson2HttpMessageConverter
  4. Json 데이터를 리턴한다.
profile
現 두나무 업비트 QA 엔지니어, 前 마이리얼트립 TQA 엔지니어

0개의 댓글