JAVA, Spring
Spring Boot 뷰 템플릿과 MVC패턴
flykimjiwon
2023. 4. 2. 19:34
반응형
-MVC 패턴
1)Model(data)
아래 코드중 Model이란 객체로 생성한 부분이 데이터가 있는 부분이다.
Firstcontoller.java
package com.example.first.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class FirstController {
@GetMapping("/hi")
public String niceToMeetYou(Model model){
model.addAttribute("username","kimjiwon");
return "greetings";
// templates/greeting.mustache -> 브라우저로 전송!
}
}
2)View Templates (presentation) - templates/greetings.mustache
아래 {{username}}이 model에서 가져오는 부분이다.
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>HI kimjiwon</h1>
<hr>
<p>아래는 </p>
<h1>{{username}}, Hello!</h1>
</body>
</html>
3)Controller (logic) - controller/FirstController
아래 코드 전체가 컨트롤러라고 할 수 있다. 그리고 Model 객체 부분이 model이다. (데이터 관리)
Firstcontoller.java
package com.example.first.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class FirstController {
@GetMapping("/hi")
public String niceToMeetYou(Model model){
model.addAttribute("username","kimjiwon");
return "greetings";
// templates/greeting.mustache -> 브라우저로 전송!
}
}
결과적으로 위와같은 페이지가 나타난다.
- 전체적으로 요약
localhost:8080/hi -> 컨트롤러 -> 컨트롤러 페이지의 model 키 밸류형태의 ( username : kimjiwon)
->뷰 템플릿(greetings.mustache)의 {{ username }}, hello!
MVC패턴의 완성이다. 정말 간단한 페이지 이지만 직접 개념을 머리에 넣어보았다는게 의미가 있는거 같다.
반응형