Spring Boot

[JAVA Spring] API

JaeGuin 2021. 1. 25. 23:45
@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;
        }
    }

저번 시간엔 MVC 방식에서 뷰를 이용해서 템플릿을 끌어와 html에 넘겨주는 방법을 했었다.

 

이번 시간에는 API를 쓰는 방법을 써보겠다.

 

 

@GetMapping("hello-string")
@ResponseBody //http에서 body 부분을 직접적으러 넣어주겠다.
public String helloString(@RequestParam("name") String name) {
	return "hello " + name;  //hello jaeguin!
}

 

 

이를 소스보기로 보면 html태그가 없이 그대로 문자가 들어간 것을 볼 수 있다.(데이타 그대로 넣어준다.)

 

 

 

 

 

API는 (Application Programming Interface) 약자로 구현 방식을 알지 못해도

서비스가 서로 커뮤니케이션할 수 있으며 애플리케이션 개발을 간소화하여 시간과 비용을 절약할 수 있다.

 

 

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

클래스 안에 클래스를 생성시켜주고 

Getter and Setter방식으로 name을 생성해준다.

 

 

json 형식으로 출력이된다.

여기서 json이란 (JavaScript Object Notation)의 약자로

key-value로 이루어진 구조이다. (과거의 xml 방식이 거의다 json방식으로 넘어갔다.)

 

 

단순 문자일 경우 string converter가 동작 객체일 경우 json converter가 동작

 

  • @ResponseBody 를 사용 
  • HTTP의 BODY에 문자 내용을 직접 반환
  • viewResolver 대신에 HttpMessageConverter 가 동작
  • 기본 문자처리: StringHttpMessageConverter
  • 기본 객체처리: MappingJackson2HttpMessageConverter
  • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음