9월 03, 2023

Spring 기초 - API 방식이란? 개념 + 예제

오늘은 Spring에서 사용하고 있는 API 방식에 대해 포스팅 해보려고 한다.





먼저 URL이 전달이 되면 API 방식에서는 Spring Controller의 @ResponseBody라는 것을 사용한다.  (위 그림 참고)

이후에 MVC 방식에서 viewResolver를 사용하였는데 API 방식에서는 HttpMessageConverter를 사용한다. 

@ResponseBody로 return값을 받으면 
기본 문자처리를 할 때는 StringHttpMessageConverter가 작동을 하고, 
객체 처리를 할 시에는 MappingJackson2HttpMessageConverter이 동작을 한다. 

예시로 TestController.java 파일을 하나 만들고
TestController.java에는 아래와 같이 적어주면 된다. 


package test.testspring.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 TestController {

     static class Test {
        private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
@GetMapping("test-string")
@ResponseBody
public String testString(@RequestParam("name")String name){

return "test "+name;
}

@GetMapping("test-api")
@ResponseBody
public Test testApi(@RequestParam("name")String name){
Test test=
new Test();
test.setName(name);
return test;
}

}

이런 식으로 작성해주면 

http://localhost:8080/test-spring?name=spring

이라고 url이 오면 name 인자에 spring이 들어가서 

test spring이 html 로 반환되는 것이다. 이것은 string으로 반환이 되었으니 StringConverter를 통해 웹브라우저로 반환이 되었을 것이다. 

반면, 

url이
http://localhost:8080/test-api?name=spring
로 들어오게 되면 
@GetMapping("test-api")
이것과 연결되어 test 라는 객체가 반환이 된다. 

여기서 test 라는 객체의 setName 메서드를 통해 name attribute가 spring으로 지정이 된 것이고 이번에는 객체이므로 JsonConverter를 통해 

{name: spring}이라는 형태로 json이 반환되는 것을 알 수 있다.