김영한님의 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 보면서 공부한 내용입니다.
생성된 프로젝트 내 src/main/resources/static
에 index.html
파일을 생성한다.
스프링 부트는 위 경로 내의 index.html
을 welcome page로 인식한다.
다음과 같이 코드를 작성한 후
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
hello My name is eunyoung! <br>
<a href="/hello">hello</a>
</body>
</html>
실행하면 웰컴 페이지가 만들어진 것을 확인할 수 있다.
하지만, 이것은 단순히 html 파일을 띄어준 정적 페이지에 불과하다.
동적 페이지를 만들기 위해서 thymeleaf 템플릿 엔진
을 사용할 것이다.
main-java 폴더에 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!");
return "hello"; // resoucres/templates에 있는 'hello.html'으로 찾아가라고 명령
}
}
viewResolver
)가 화면을 찾아서 처리viewName
매핑resources:templates/
+{ViewName}+ .html
이후 templates에 hello.html을 생성하여 아래와 같이 코드를 작성한다.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<!--
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>
<!--
HelloController에서 선언한 키값(data)의 value(는 영어로 hello!)가 ${data}안에 들어감
-->
</body>
</html>
아래 사진은 http://localhost:9090/hello의 실행 원리를 그림으로 표현한 것이다.
코드를 살펴보자
@Controller
어노테이션을 꼭 붙여야한다.@GetMapping
어노테이션은 http GET 요청을 특정 메소드와 매핑시켜주기 위한 어노테이션으로 파라미터안에 url을 적는다.hello
함수는 위의 get 요청을 처리하기 위한 메소드로, 파라미터로 model을 받아온다.model.addAttribute("data","hello!!")
에서는 model에게 data를 넘기게 되는데 이때 data의 값은 hello!!이다.ViewResolver
가 hello.html을 찾아서 화면을 띄워준다
hello를 클릭하면 아래와 같은 화면이 뜨는 것을 확인할 수 있다.