이 영역을 누르면 첫 페이지로 이동
컴01기 블로그의 첫 페이지로 이동

컴01기

페이지 맨 위로 올라가기

컴01기

힝입니다.

[Spring] MVC 와 템플릿 엔진

  • 2021.01.12 05:44
  • etc/Spring

MVC란? Model, View, Controller 의 약자.

어플케이션을 3가지의 역할로 구분한 '개발 방법론' 이다.

이 역할들이 서로 상호작용한 결과물이 사용자에게 보여지게 되는 것이다.

 

  1. 사용자가 Controller를 조작하면
  2. Controller가 Model을 호출하고
  3. Model이 데이터를 이용하여 만들어낸 결과를 Controller 에게 리턴해서
  4. Contorller는 그 결과를 View에 반영하고
  5. View는 사용자에게 보여진다.

 

  • HelloController 변경
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package hello.hellospring.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@Controller
public class HelloController {
 
    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data", "spring!!");
        return "hello";
    }
 
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam(value = "name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template";
    }
 
}
 
Colored by Color Scripter
cs

 

  • resources > template 에 hello-template.html 파일 추가
1
2
3
4
5
6
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello. ' + ${name}"> hello! empty </p>
</body>
</html>
Colored by Color Scripter
cs

thymeleaf 은 템플릿 엔진이다.

thymeleaf의 장점은, 템플린 엔진 없이, 즉 서버 없이, 작성한 html 파일을 그냥 볼 수 있다는 것이다.

(템플릿 엔진이 동작하면 name 값을 받아와서 내용이 바뀐다.)

 

서버 없이, 작성한 html을 '그냥' 볼 때

  • hello-template.html 우클릭 > Copy Path > Absolute Path > 웹 브라우저에서 접속

 

템플릿 엔진을 동작시켜서 볼 때 (값은 안 줬음)

  • localhost:8080/hello-mvc

이렇게 그냥 보면, 오류가 난다. 

'name' is not present

 

원래 default 가 required = true 로 설정되어 있음을 알 수 있다.

 

  • HelloController에서 required = false 로 설정해준다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package hello.hellospring.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@Controller
public class HelloController {
 
    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data", "spring!!");
        return "hello";
    }
 
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam(value = "name", required= false) String name, Model model){
        // 외부(웹)에서 parameter 를 받아올 예정!
        model.addAttribute("name", name);
        return "hello-template";
    }
 
}
Colored by Color Scripter
cs

 

 

  • Recompile 한 후에 localhost:8080/hello-mvc 접속

 

템플릿 엔진을 동작시켜서 볼 때 (값 줬다!)

 

 

  • localhost:8080/hello-mvc?name=uhhyunjoo

 

 

동작 방식 설명

 

helloMvc에서 Request한 Parameter "name"을 uhhyunjoo로 받아오면,

String name의 name이 uhhyunjoo 가 되는 것이고,

model 에 "name" 이라는 attributeName 으로 name, 즉 uhhyunjoo 가 들어가게 되는 것이다.

 

그럼 이게 모델에 담겨서 hello-template 으로 넘어가게 된다.

 

'$' 표시는 모델에서 값을 꺼낸다는 뜻인데,

${name} 이므로 모델에서 key가 name인, 값 uhhyunjoo를 꺼내게 된다.

꺼내서, 치환해주는게 템플릿 엔진의 역할인 것이다.

 

http get 방식으로, 탬플릿 엔진이 변환을 해서, 웹브라우저에 반환해준 것이다.

(정적일 때는 이 변환을 하지 않았었다.)

소스를 보면, uhhyunjoo로 변환이 됐다는 것을 알 수 있다.

 

 

저작자표시 (새창열림)

'etc > Spring' 카테고리의 다른 글

[Spring] API 방식  (0) 2021.01.13
[Spring] 정적 컨텐츠 (.html) 가져오기  (0) 2021.01.04
[Spring] Port 8080 was already in use.  (0) 2021.01.04
[Spring] 프로젝트 빌드하고 실행하기  (0) 2021.01.04
[Spring] spring-boot-devtools 라이브러리 추가하기  (0) 2021.01.03

댓글

이 글 공유하기

  • 구독하기

    구독하기

  • 카카오톡

    카카오톡

  • 라인

    라인

  • 트위터

    트위터

  • Facebook

    Facebook

  • 카카오스토리

    카카오스토리

  • 밴드

    밴드

  • 네이버 블로그

    네이버 블로그

  • Pocket

    Pocket

  • Evernote

    Evernote

다른 글

  • [Spring] API 방식

    [Spring] API 방식

    2021.01.13
  • [Spring] 정적 컨텐츠 (.html) 가져오기

    [Spring] 정적 컨텐츠 (.html) 가져오기

    2021.01.04
  • [Spring] Port 8080 was already in use.

    [Spring] Port 8080 was already in use.

    2021.01.04
  • [Spring] 프로젝트 빌드하고 실행하기

    [Spring] 프로젝트 빌드하고 실행하기

    2021.01.04
다른 글 더 둘러보기

정보

컴01기 블로그의 첫 페이지로 이동

컴01기

  • 컴01기의 첫 페이지로 이동

검색

메뉴

  • 홈
  • 태그
  • 방명록

카테고리

  • 분류 전체보기 (87)
    • 📰논문 리뷰 (16)
    • 🍒회고록 (4)
    • 🖤네이버 ai tech (0)
    • ✨글쓰는힝 (1)
    • 🔥취준일기 (2)
    • 🎲유니티 (2)
    • 🔨삽질 (10)
    • 📚 서적 리뷰 (4)
    • 🐹알고리즘 (4)
    • 😎정리하는 카테고리 (4)
    • 📝CS 공부 (6)
      • 운영체제 (1)
      • 네트워크 (4)
      • 리팩토링 (1)
    • etc (22)
      • 혼공단 (7)
      • Spring (7)
      • JS (1)
      • OpenCV (2)
      • Unity (5)

최근 글

인기 글

댓글

태그

  • 혼공학습단
  • github
  • 혼공SQL
  • unity
  • 혼공단
  • 백준
  • 혼공머신
  • 회고록

나의 외부 링크

  • Github
  • Youtube

정보

힝님의 컴01기

컴01기

힝님

방문자

  • 전체 방문자
  • 오늘
  • 어제

블로그 구독하기

  • 구독하기
  • RSS 피드

티스토리

  • 티스토리 홈
  • 이 블로그 관리하기
  • 글쓰기
Powered by Tistory / Kakao. © 힝님. Designed by Fraccino.

티스토리툴바