1. MVC와 템플릿 엔진
- MVC(Model View Controller)
01. Controller
- demo/src/main/java/hello/demo/controller/HelloController
package hello.demo.controller;
import org.springframework.stereotype.Controller;
@Controller
public class HelloController {
//MVC 방식
// WebApplication에서 /hello로 접근을 하면 아래에 밑에 메소드를 호출
// Get은 get, post 방식 중 get 방식으로 url로 접근했을 때 호출
@GetMapping("hello")
public String hello(Model model) {
// key,value로 설정
model.addAttribute("data","spring!!");
// template 중 hello라는 이름을 가진 template에 전달, 여기서는 hello.html
// resources:templates/ +{ViewName}+ .html, viewname은 return 값
return "hello";
}
@GetMapping("hello-mvc")
// 기본적으로 required가 true이기 때문에 값을 넣어줘야 한다
// value = "name", required = false로 하면 값을 넘겨주지 않아도 된다
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
02. View
- demo/src/main/resources/templates/hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello1 ' + ${name}">hello! empty</p>
</body>
</html>
03. 실행