View 환경설정

숭맹이·2025년 4월 21일

김영한님의 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 정리

1. Welcome Page 설정

Spring Boot는 기본적으로 resources/static/ 경로에 index.html 파일이 존재하면 별도의 컨트롤러 없이 자동으로 Welcome Page를 제공해줍니다.

설정 방법

src/main/resources/static/index.html 파일 생성:

<!DOCTYPE HTML>
<html>
<head>
<title>Hello</title>
<meta charset="UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

동작 원리

  • 내장 톰캣 서버가 정적 리소스 경로를 서빙합니다.
  • /로 접근 시 static/index.html을 찾아서 반환합니다.

참고: Spring Boot 공식 문서 - Welcome Page


2. Thymeleaf 템플릿 엔진 연동

정적 페이지만으로는 한계가 있습니다. 동적인 View 처리를 위해 템플릿 엔진을 도입해야 합니다. Spring Boot에서는 Thymeleaf가 기본 선택지 중 하나입니다.

2.1 Thymeleaf 의존성 추가

Spring Boot Starter를 이용하면 간편하게 추가할 수 있습니다.

<!-- build.gradle 사용 시 -->
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

2.2 HelloController 작성

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

@Controller
public class HelloController {

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

2.3 Thymeleaf 템플릿 작성

src/main/resources/templates/hello.html:

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

2.4 동작 흐름 정리

  1. 브라우저가 /hello 요청
  2. HelloControllerhello() 메소드 실행
  3. Modeldata 값을 담아 View 이름(hello) 반환
  4. viewResolverresources/templates/hello.html를 찾아 렌더링
  5. 템플릿 엔진(Thymeleaf)이 ${data}를 "hello!!"로 치환하여 결과 HTML을 반환

실행 URL: http://localhost:8080/hello


3. Spring Boot ViewResolver 기본 설정

Spring Boot의 기본 ViewResolver 매핑 규칙:

  • 템플릿 폴더: resources/templates/
  • 파일 확장자: .html
  • View Name: 컨트롤러 메서드에서 리턴한 문자열과 일치하는 파일명을 찾는다.
View Name "hello" -> templates/hello.html

4. 개발 생산성 향상 Tip: DevTools 사용

개발 중 HTML 파일 변경 시 서버 재시작 없이 반영하고 싶다면 spring-boot-devtools를 추가하면 됩니다.

<!-- build.gradle 사용 시 -->
dependencies {
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
}

주의사항: HTML 파일은 Recompile 해야 반영됩니다. (IntelliJ 기준 Build > Recompile)

profile
👨🏻‍💻 Backend Developer

0개의 댓글