Welcome Page 만들기

[resources/static/index.html]

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

실행 결과

 

 

Web

Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest

docs.spring.io

 


thymeleaf 템플릿 엔진

  • 타임리프는 HTML, XML, JavaScript, CSS, text를 생성하기 위한 자바 템플릿 엔진이다.
  • 스프링부트 매뉴얼: Spring Boot Features
 

Spring Boot Features

Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest

docs.spring.io

 

Template Engine에는 위와 같이 4가지가 있는데, 김영한 선생님의 강의는 Thymeleaf를 사용한다.

 

@Controller
public class HelloController {
     @GetMapping("hello")
     public String hello(Model model) {
     model.addAttribute("data", "hello!!");
     return "hello";
 }
}
  • 컨트롤러란?
    Spring Framework는 MVC(Model, View, Controller) 패턴을 사용하고 있고, 이 중에 Controller는 화면(View)와 비즈니스 로직(Model)을 연결하는 다리 역할을 한다. 즉, 화면에서 어디로 가달라고 요청하면 주소를 받아들여 어디로 갈지 분석하고 맞는 길로 연결시켜주는 역할을 한다.
  • @Controller: 이 어노테이션으로 인하여 내부적으로 Controller의 역할을 할 수 있게 된다.
  • @GetMapping: 요청 주소와 실제 주소를 get 방식으로 mapping하는 어노테이션으로, 마치 if문과 비슷하다.
  • model.addAttribute(String name, Object value): name은 key값이며, value는 value값이다. name 이름으로 value 객체를 추가하는 코드이다.
  • return "hello": hello 파일을 찾아서 렌더링한다.

[resources/templates/hello.html]

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org"> <!--thymeleaf 사용 선언-->
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>
  • <html xmlns:th="http://www.thymeleaf.org">: 타임리프를 사용하겠다고 선언
  • <p> 태그의 th:text에서 th는 thymeleaf를 의미한다.
  • <p> 태그의 ${data}가 Controller의 hello!!로 치환된다.

실행 결과

 

thymeleaf 템플릿엔진 동작 확인

동작 환경 그림

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

+ Recent posts