본문 바로가기
Framekwork/SPRING

[자바/스프링] View 환경설정 (add. thymeleaf )

by 아이엠제니 2023. 2. 9.

 

 

✔️ 스프링 부트가 제공하는 Welcome Page 기능

  • static/index.html 을 올려두면 Welcome page 기능을 제공함

 

💾 resources/static/index.html

<!doctype html>
<html lang="ko">
<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</title>
</head>

<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

 

 

✔️ thymeleaf 템플릿 엔진

 

💾 main > java > hello > hellospring > controller > HelloController

package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("hello") // 웹 애플리케이션에서 /hello 라고 들어오면, 이 메서드를 호출함
    public String hello(Model model) {
        model.addAttribute("data", "hello!!"); // 데이터를 "hello!!" 라고 넘길 거임
        return "hello"; // resources > templates에 있는 hello를 찾아서 렌더링 해라
    }
}

 

💾 main > resources > templates > hello.html

<!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</title>
</head>
<body>
<!-- ${data}는 `HelloController`에 있는 데이터 값을 가져옴-->
<p th:text="'안녕하세요 '+${data}">안녕하세요. 손님</p>
</body>
</html>

 

 

✔️thymeleaf 템플릿 엔진 동작 확인

  • 스프링 부트에 톰캣 서버를 내장하고 있다!

  • model(data:hello!!)
    • '모델'에다가 '데이터'는 '헬로우'라고 넣어 놓음
    • 그리고 'hello'를 return 함
      • resources > templates 의 밑에 있는 'hello'를 찾음

 

  • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버(`viewResolver`)가 화면을 찾아서 처리함
    • 스프링 부트 템플릿 엔진 기본 viewName 매핑
    • `resources:templates/`+{ViewName}+`.html`

 

+ 번외

  • `spring-boot-devtools` 라이브러리를 추가하면, `html` 파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경 가능
  • IntelliJ 컴파일 방법: 메뉴 build > Recompile

 

 

 

[스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술] 강의 기록
300x250