Java

spring View, 템플릿 엔진

blackbearwow 2025. 2. 7. 17:34

1. Spring View

스프링 부트에서 View는 두가지로 나눌 수 있다. 누가 언제 요청하든 똑같은 대답을 해주는 static과 상황마다 다른 대답을 해주는 templates로 나뉜다. 

1.1. static view

<!DOCTYPE HTML>
<html>
<head>
    <title>Hello there</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    Hello there
    <a href="/hello">hello</a>
</body>
</html>

src - main - resources - static폴더에 hello.html을 만들어 보자. 그리고 SpringApplication을 실행후 웹에서 127.0.0.1:8080/hello.html를 접속하면 화면이 보일것이다. 

이처럼 static폴더에 html파일을 만들면 스프링 앱에서 별다른 조치 없이 자원에 접촉이 가능하다. index.html을 파일 이름으로 하면 127.0.0.1:8080에 접속해도 화면이 보일 것이다. index.html만 생략 가능하다.

1.2. templates

templates는 템플릿 엔진이라는 외부 라이브러리를 사용한다.

MVC패턴의 model의 데이터가 view에 영향을 미치는데, 이때 model의 데이터를 어떻게 처리할지 문법적으로 다루는 라이브러리이다. 대표적으로 freemarker, thymeleaf, mustache 템플릿 엔진이 있다. 우리는 thymeleaf엔진을 사용해보자.

 

src - main - java - hello.hello-spring에 controller라는 패키지를 만들어준다. 그리고 그 패키지에 HelloController클래스를 만들어준다.

package hello.hello_spring.controller;

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

@Controller
public class HelloController {

    @GetMapping("/")
    public String hello(Model model) {
        model.addAttribute("data", "hello!!");
        return "index";
    }
}

 

그리고 src - main - resources - templates에 index.html파일을 만들어준다. 

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Hello</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
  <p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

그리고 SpringApplication을 실행후 127.0.0.1:8080를 접속해보면 다음과 같은 화면이 뜰것이다.

 

컨트롤러에서 문자를 반환하면 viewResolver가 화면을 찾아 처리한다.

 

여기서 의문이 든다. 만약 static 에서 index.html이 있고 templates에도 index.html이 있다면 어떤 것이 응답될까? 정답은 templates의 index.html이 응답된다. 스프링 부트는 웹 요청을 받으면 먼저 스프링 컨테이너에 해당되는것이 있는지 살펴보기 때문이다. 컨트롤러에 해당되는 웹 요청이 없을 경우에 static에서 해당되는 경우가 있는지 찾는 것이다.