Post

Spring MVC의 핵심: 코드로 보는 Controller, Model, View의 역할

Model, View, Controller


하나하나에 대해 설명을 해보자면

Controller 는 클라이언트 의 요청을 직접적으로 받는 곳이다. 예를들어 사용자가 /user 라는 endpoint 로 들어 온다면 이걸 처음에 Controller 가 가지고 간다!

Model 은 Controller 가 클라이언트에게 응답으로 돌려주고픈 데이터를 모은곳이다

마지막으로 View는 Model 에 들어있는 데이터를 이용해서 화면에 보이는 무언가를 제공하는 역할을 한다!

Code 로 보자!


우선 사용자가 Controller 에 요청을 보낸다!

1
2
3
4
5
6
7
@Controller
public class TestController {
    @GetMapping("index")
    public String getMainPage(Model model) {
        ...
    }
}

그럼 그 안에서 model 에 필요한 정보를 담아준다

1
2
3
4
5
@GetMapping("index")
    public String getMainPage(Model model) {
        model.addAttribute("greeting", "Hello World");
        return "index";
    }

그렇게 되면 resources/template 하위의 index.html 이 불러와진다!

1
2
<!--index.html-->
<h1>${greeing}</h1>
This post is licensed under CC BY 4.0 by the author.

© 병욱. Some rights reserved.