김영한님의 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 정리
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을 찾아서 반환합니다.정적 페이지만으로는 한계가 있습니다. 동적인 View 처리를 위해 템플릿 엔진을 도입해야 합니다. Spring Boot에서는 Thymeleaf가 기본 선택지 중 하나입니다.
Spring Boot Starter를 이용하면 간편하게 추가할 수 있습니다.
<!-- build.gradle 사용 시 -->
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}
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";
}
}
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>
/hello 요청HelloController의 hello() 메소드 실행Model에 data 값을 담아 View 이름(hello) 반환viewResolver가 resources/templates/hello.html를 찾아 렌더링${data}를 "hello!!"로 치환하여 결과 HTML을 반환실행 URL: http://localhost:8080/hello
Spring Boot의 기본 ViewResolver 매핑 규칙:
resources/templates/.htmlView Name "hello" -> templates/hello.html
개발 중 HTML 파일 변경 시 서버 재시작 없이 반영하고 싶다면 spring-boot-devtools를 추가하면 됩니다.
<!-- build.gradle 사용 시 -->
dependencies {
developmentOnly 'org.springframework.boot:spring-boot-devtools'
}
주의사항: HTML 파일은 Recompile 해야 반영됩니다. (IntelliJ 기준 Build > Recompile)