View Templates, MVC 패턴 뿌시기

Gyuhan Park·2022년 7월 23일
0

spring

목록 보기
4/18

MVC 패턴

Model : data
View : screen
Controller : logic

view template directory

src > main > resource > templates > mustache 파일 생성

controller directory

src > main > java > 기본 package > controller package 생성 > controller java class 생성

mustache

: view template을 만들어주는 도구. view template engine 중 하나.

mustache plugin 설치

mustache를 확장자로 인식하지 못할 경우 plugin 설치
help > find action > mustache 검색 > handlebars/mustache 설치

# Controller

package com.example.demo.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 hello(Model model){
        model.addAttribute("username", "Park");
        return "greetings"; // templates/greetings.mustache 를 찾아서 브라우저에 전송
    }
}

# View

<!-- doc치고 tab치면 html 기본 템플릿 코드 생성 -->
<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>hello, Mr.{{username}} !</h1>
</body>
</html>

뷰 템플릿이 출력되기까지의 실행 흐름

controller : client 로부터 요청받음
view : 페이지를 만들어주고
model : 최종 페이지에 쓰일 데이터들을 view에 전달

[뷰 템플릿이 출력되는 과정]
1. controller가 브라우저로부터 request 받음
2. 적절한 어노테이션이 붙은 메소드 실행(ex> @GetMapping)
3. view template에서 사용할 데이터들을 model 오브젝트로 생성
4. model을 view template에 넘겨주고 화면 출력.

# mustache 한글이 깨짐 이슈

build.gradle > id 'org.springframework.boot' version '2.7.0'을 '2.6.8'로 변경 -> 우측에 있는 코끼리 모양 아이콘 클릭

profile
단단한 프론트엔드 개발자가 되고 싶은

0개의 댓글