본문 바로가기
[ Development ]/[ Back-end ] Spring 기본

[Spring 스프링] 2-2. MVC와 템플릿 엔진

by dev charlotte 2023. 10. 3.

* MVC와 템플릿 엔진

Model - View - Controller

 

이전에는 뷰와 컨트롤러를 구분하지 않고 하나로 진행했으나 

View는 화면을 구성하고 화면 관련된 것에

Controller는 로직, 내부적 처리하는 것에 집중하도록 한다

 

helloController에 

// 기존 내용
@Controller
public class HelloController {
 @GetMapping("hello")
 public String hello(Model model) {
 model.addAttribute("data", "hello!!");
 return "hello";
 }
}

// 하단의 내용 추가
@Controller
public class HelloController {
 @GetMapping("hello-mvc")
 public String helloMvc(@RequestParam("name") String name, Model model) {
 model.addAttribute("name", name);
 return "hello-template";
 }
}

외부에서 파라미터 받을 것

addAttribute(key, name)으로 구성

return 뒤에 명시된 곳으로 이동한다

 

templates 에 hello - templates.html 생성

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

타임리프의 장점은 파일 작성 후 서버 없이 바로 열어봐도 볼 수 있음

( 파일 우클릭 앱솔루트 카피 해서 주소 창에 파일 열고 소스 코드 확인 )

 

템플릿 엔진으로 동작하면 hello!empty가 th text로 치환된다 

 

 

public String helloMvc(@RequestParam(value = "name", required = true) String name, Model model) {

http://localhost:8080/hello-mvc?name=spring

 

 

동작 방식

주소에서 name=spring!!!으로 넘어가면 컨트롤러에서 name = spring!!!으로 넘어가고 모델에 담겨

템플릿으로 넘어가면 ${name}은 모델의 키값이 name에서 값을 꺼내는 것

 

viewResolver 뷰를 찾아주고 템플릿 엔진을 연결해준다