MVC란 Model, View, Controller의 앞 글자만 따온 약자이다.
이는 동적 콘텐츠를 만들 때 사용된다.
우선 Controller의 작동 방식부터 알아보겠다.
1. Controller는 "URL"요청에 따라 어떤 Controller가 사용되는지 결정된다.
예를 들어 localhost:8080/hi-mvc?nickname=byhy0 라는 요청이 왔을때는 서버에서는 hi-mvc라는 컨트롤러가 있는지를 먼저 확인한다.
@GetMapping("hi-mvc")
public String helloMvc(@RequestParam("nickname") String nickname, Model model){
model.addAttribute("nickname", nickname);
return "hi-template";
}
@GetMapping("hi-mvc") 라고 hellowMvc라는 메서드 위에 적어뒀기 때문에
localhost:8080/hi-mvc라는 요청에 helloMvc 메서드가 실행된다.
2. @RequestParam("nickname") 요청에 'nickname'이라는 변수에 들어있는 값을 nickname이라는 매개변수에 저장한다.
3. model.addAttribute("nickname", nickname); model이라는 객체에 nickname이라는 key에 매개변수로 받아온 nickname
즉, 이 예제에서는 byhy0가 저장되는 것이다.
4. return "hi-template" hi-template.html 파일에 model을 준다라고 생각하기.
model을 객체로 추가한 데이터를 View로 전달됩니다.
View는 이 데이터를 사용해서 렌더링합니다.
이제 template 파일에 있는 hi-template.html에 이 데이터들이 전송됩니다.
hi-template.html는 Controller에서 받아온 데이터를 사용하기 위해 템플릿 엔진을 활용해야 합니다.
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
<html xmlns:th="http://www.thymeleaf.org"> 는 템플릿 엔진인 Thymeleaf를 사용하기 위해 적어줘야 합니다.
th:text 는 타임리프에서 제공되는 속성입니다.
사용법은 다음과 같습니다.
<p th:text="'hello ' + ${nickname}">hello! empty</p>

참고자료: 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 - 김영한