@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name"), String name) {
return "hello "+name;
}
- @ResponseBody : httop의 body부분에 return하는 데이터를 직접 넣겠다는 의미
- `return "hello "+name;` : 내가 요청한 클라이언트에 그대로 값이 들어감.
서버 실행 후 http://localhost:8080/hello-string?name=spring!!!!!!!!!!
로 접속
페이지에 hello spring!!!!!!!!!!
이 뜬 것을 확인
페이지 소스 코드 보기를 하면 html 코드도 없이 정말 문자열만 화면에 가져온 것을 확인할 수 있음
@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=김아무개
서버로 접속했다면 아래와 같은 JSON 형식의 결과가 나온다.
{
"name": "김아무개"
}
만약 @ResponseBOdy
가 있고 객체를 반환한다면 기본으로 JSON 으로 결과값을 받아온다고 생각하면 된다!
(참고) getter setter 방식은 자바 빈 표준 방식, 또는 프로퍼티 접근 방식이라고 한다.
웹 브라우저에서 먼저 http://localhost:8080/hello-api
를 친다.
톰켓 내장 서버에서 hello-api
가 왔어! 라고 인식 후, 스프링에 서버를 던져준다.
스프링은 hello-api
가 있는지를 확인한다.
4-1. @ResponseBody
가 없는 경우 : viewResolver
에게 던짐
4-2. @ResponseBody
가 없는 경우 : http에 내가 받은 데이터를 그대로 넘겨야 되겠구나~!
근데 객체네?
@ResponseBody
가 없는 경우에는 viewResolver
가 동작함JSON 형식으로 변환한 데이터를 요청한 웹 브라우저 또는 서버에 응답해줌(보내줌)
viewResolver
대신에 HttpMessageConverter
가 동작StringHttpMessageConverter
MappingJackson2HttpMessageConverter
참고 - 클라이언트의 HTTP Accept 헤더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서
HttpMessageConverter
가 선택된다.
- HTTP Accept 헤더 : HttpMessage 스펙을 보면 요청을 할 때 어떠한 포맷으로 받고 싶다고 하면 이것을 사용
정적 컨텐츠 - 파일을 그대로 내려준다.
MVC와 템플릿 엔진 - 템플릿 엔진을 model view 방식으로 쪼개서 view를 템플릿 엔진으로 html 파일을 프로그래밍 방식으로 rendering해서 rendering이 된 html을 고객에게 전달해준다.
API 방식 - 객체를 HttpMessageConverter를 사용하여 JSON 방식으로 반환해준다. (view 없이)