인프런 김영한 선생님의 Spring 강의를 듣고 정리한 내용으로 시리즈로 연재할 계획입니다.
Controller
가 @GetMapping
annotation에 인자로 전달받은 URL을 처리하고, 리턴값으로 문자를 반환하면 ViewResolver
가 화면을 찾아서 처리한다. 스프링 동작환경은 크게 3가지로 나뉜다. 하나씩 알아보자.
첫번째는 정적컨텐츠
이다. 이는 .html 형식의 파일을 그대로 웹사이트에 올려주는 것을 말한다.
@Controller
public class HelloController {
@GetMapping("hello-static")
public String hellolee(Model model) {
model.addAttribute("data","hello!!");
return "hello-static";
}
}
GetMapping()
annotation에 인자로 전달된 주소로 접속을 하면, 해당 함수가 실행되는 구조이다. hellolee () 함수에 model객체가 인자로 전달되면 viewController
에서 model인자의 키 값 "data"에 "hello!!" 를 추가해준다. "hello" 문자열 리턴을 통해 "hello-static.html" resource/static/hello-static.html
파일을 찾아 웹사이트에 올려준다.
말그대로 html 파일을 그대로 웹사이트에 올려주는 정적 컨텐츠이다.
두번째는 MVC와 템플릿 엔진
이다. MVC
는 Model,View,Controller의 약자이다
@Controller
public class HelloController {
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
정적 컨텐츠
와 다른점은, @RequestParam
annotation이다. 이게 무슨 의미일까? 해당 웹사이트의 URL은 localhost:8800/hello-template?name=ddd
이다. (ddd는 내가 임의로 전달한 값이다.) 이 주소로 접근을 하면 viewResolver
가 template/hello-template.html
에 접근하여 $(name)
에 "ddd"
가 들어가게 된다. (이 역할은 템플릿 엔진
이 처리한다. 해당 예제에서는 템플릿 엔진 thymeleaf
를 사용하고 있다.
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
결과로 웹사이트에 hello ddd가 나타난다.
세번째는 API 방식이다. 이는 json 형식으로 웹사이트에 표기한다.
API방식의 가장 큰 특징은 뷰 리졸버
없이 동작한다는 것이다.
API 방식에는 크게 2가지가 있다. 하나는 @ResponseBody
문자반환, 다른 하나는 @ResponseBody
객체 반환이다. 하나씩 살펴보자
@Controller
public class HelloController {
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
}
return "<html><body>dmskdkms</body></html>"
과 같이 html을 전달할 수도 있다.@Controller
public class HelloController {
@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;
}
}
객체를 반환하게 된다면, 인자로 전달된 값을 json형식의 데이터로 표현하게 된다. 해당 경우에는 {"name":"value"}
를 반환하게 된다.
두 API 방식 모두 뷰 리졸버 대신에
HttpMessgageConverter
가 동작하며, 문자의 경우에는StringHttpMessageConverter
가, 객체의 경우에는MappingJackson2HttpMessageConverter
가 동작한다.
Intellj 부가기능 : command + N -> getter setter 생성 가능!