Spring Boot는 resources/static 또는 resources/templates 폴더에 index.html을 만들면 이 페이지를 Welcome 페이지로 만들어준다.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Hello</title>
</head>
<body>
정적 컨텐츠
<a href="/hello">hello</a>
</body>
</html>
index.html을 이처럼 작성하면
템플릿 엔진을 쓰게 된다면 html에서 원하는 부분의 모양을 바꿀 수 있다. 즉, 동적 페이지를 만들 수 있게 된다.
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model){
model.addAttribute("data", "hello!!");
return "hello";
}
}
HelloController.java에는 위와 같이 작성한다.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Hello</title>
</head>
<body>
<p th:text="'안녕하세요. '+${data}">안녕하세요. 손님</p>
</body>
</html>
hello.html에는 위와 같이 작성한다.
th: thymeleaf의 th를 의미
여기에서 {data}는 HelloController.java에서 model.addAttribute에서 key로 넣었던 "data"를 의미하며, 이 코드에서 Value는 "hello!!"이다. 따라서 ${data} 이 부분이 hello!!로 바뀌어 웹 브라우저에 띄워진다.
IntelliJ IDE가 실행하는 것이 아닌 빌드 파일을 만들어 실행해본다.
1. IntelliJ에서 서버를 중지시킨다.
2. cmd를 프로젝트 폴더 경로 위치에서 실행한 후 gradlew.bat build를 실행한다. (맥의 경우 ./gradlew build 입력)
따라서 서버 배포 시 hello-spring-0.0.1-SNAPSHOT.jar 파일만 서버에 넣어준 후 실행하면 된다.
gradlew clean build를 입력해 빌드를 다시 시작한다.
본 포스팅은 inflearn 김영한 강사님의 "스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술" 강의에 기반하여 작성되었습니다.
강의 링크
썸네일 생성: Thumbnail Maker