개인 공부/인프런

[JavaSpring] API

planting grass 2023. 3. 21. 11:36
728x90

API

다시 콘트롤러로 돌아가 아래 코드를 입력해주자

package study.studyspring.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;

@Controller
public class StudyController {

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello!!");
        return "hello";
    }
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam(value = "name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }

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

여기서 @ResponseBody는 처음볼텐데 http에서 head와 body로 나뉘어 지는데 여기서 body에 직접 넣어주겠다는 뜻이다.

즉 return값인 “hello” + name이 들어간다는 것이다.
(name이 바뀌면 다른 결과값이 나옴)

여기서 페이지 소스보기를 하면

html 태그가 아예 없다는걸 확인이 가능하다.

아래 코드는 문자열이 아니라 데이터를 이용해보았다.

package study.studyspring.controller;

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

@Controller
public class StudyController {

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello!!");
        return "hello";
    }

    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam(value = "name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }

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

    @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=really? 로 들어가보니 아래와 같이 바뀌었다.

이 표기는 json이라는 방식이다.

  • JSON이란?직역하자면 자바 스크립트 객체 표기법이다.
  • 즉, 데이터를 교환하고 저장하기 위해 사용되는 경량의 data 교환 방식이다.
  • JSON(JavaScript Object Notation)

과거에는 xml방식을 사용하다 html태그를 비롯한 추가로 달아야하는 코드가 많다보니 json이 최근에는 주류가 되었다고 한다.

자바 스프링은 @ResponseBody를 쓰면 기본적으로 json방식을 사용한다고 보면 된다.

  • Getter, Setter 기능class 앞에 get이 붙으면 getter, set이 붙으면 setter가 된다.
  • 단축키는 Alt + Insert 다.

왜 getter, setter를 쓸까?

@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;
        }
    }

위 코드에서 private로 name을 불렀기 때문에 외부에서 호출이 안된다.

때문에 라이브러리를 비롯해서 사용할때 getter, setter를 이용해서 사용해야 한다.

hello-api 동작의 자세한 설명

  1. http://localhost:8080/hello-api?name=really? 를 입력하면 내장된 톰켓 서버에서 spring에 hello-api가 왔다고 인지하게 해준다.
  2. spring에서 Controller에서 Mapping을 통해 코드가 동작한다.
  3. ResponseBody 어노테이션이 붙어있기 때문에 MVC와는 다르게 view로 넘어가지 않고 바로 return값을 웹에 전달해준다.
  4. 코드를 보면 알겠지만 return되는 대상이 객체가 된다.
    (MVC는 폴더를 찾았지만 API는 폴더를 찾는게 아님)
  5. HttpMessageConverter가 동작해서 JsonConverter나 StringConverter로 동작하게 된다.
    • JsonConverter는 MappingJackson2HttpMessageConverter가 처리한다.
      • why Jackson인가?
        ⇒ 유명한 라이브러리 중 한개임 자바스프링은 이친구를 기본으로 사용함
    • String Converter는 StringHttpMessageConverter가 처리한다.
  6. 지금은 객체가 return값이기 때문에 Json으로 반환해준다.
728x90