It won't hurt to try

[스프링 입문]7.MVC와 템플릿 엔진 본문

JAVA/스프링 입문

[스프링 입문]7.MVC와 템플릿 엔진

yongki.doki 2021. 8. 1. 14:33

hello-template를 여는 간단한 테스트 페이지

 

<name파라미터가 있을때>

화면 출력내용

<파라미터가 없을때>

화면 출력내용

 

controller

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-template")
    public String helloTemplate(@RequestParam(value = "name", required = false, defaultValue = "default") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }
}

 

view

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<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>hello-template</title>
</head>
<body>
  <p th:text="'hello ' + ${name}">mock hello</p>
</body>
</html>

 

설명

@GetMapping("mappingName")

 - www.test.com/mappingName  이라는 URL이 있다고 가정하면, mappingName이 컨트롤러와 맵핑하기위한 값이다.

Model object

 - Model은 MVC패턴에서 M에 해당된다.

 - 우리가 흔히 서버에서 화면으로 값을 넘겨줄때 attribute, parameter속성을 이용하는 경우가 많은데, Model 객체가 addAttribute같은 함수를 활용해서 값을 넘겨준다.

return 

 - @GetMapping이 되어있는 함수에서 return값은 반환하고 싶은 view파일의 이름이다.

 - 스프링 컨테이너 안의 viewResolver를 통해 파일을 찾는다.

<html xmlns:th="http://www.thymeleaf.org">

 - 여기서 xmlns는 xml NameSpace을 줄여서 표기한 것이다.

 - html을 렌더링할때 thymeleaf템플릿 엔진을 활용해서 렌더링한다.

${}

 - 이 문법은 thymeleaf의 문법이기도 하고 다른 언어나 프레임워크에서도 자주 사용되는 문법이다. 이 안에서는 model attribute의 값을 키를 통해 읽어드린다. ${key}

 

300x250
300x250
Comments