라이브러리 살펴보기
Gradle은 의존관계가 있는 라이브러리를 함께 다운로드한다.
스프링 부트 라이브러리
- spring-boot-starter-web
- spring-boot-starter-tomcat:톰캣(웹서버)
- spring-webmvc:스프링 웹 MVC
- spring-boot-starter-thymeleaf:타임리프 템플릿 엔진(view)
- spring-boot-starter(공통): 스프링 부트 + 스프링 코어 + 로깅
- spring-boot(spring-core)
- spring-boot-starter-logging(logback, slf4j)
테스트 라이브러리
- spring-boot-starter-test
- junit: 테스트 프레임워크
- mockito: 목 라이브러리
- assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리
- spring-test: 스프링 통합 테스트 지원
View 환경설정
Welcome Page 만들기
- src -> main -> resources -> static에서 우클릭 -> File -> index.html 파일 생성
<!DOCTYPE HTML>
<html>
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charse=UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>
thymeleaf 템플릿 엔진
- src -> main -> java -> 프로젝트 폴더 위에서 우클릭 -> new -> package -> 패키지명: controller 입력 -> 생성된 controller 패키지 위에서 우클릭 -> new -> java class -> 파일명: 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")
public String hello(Model model) {
model.addAttribute("data", "hello!!");
return "hello";
}
}
- src -> main -> resources -> templates 패키지 우클릭 -> new -> File -> 파일명: hello.html
<!DOCTYPE HTML>
<html 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>
</body>
</html>
- 이제 Run을 클릭하고 localhost:8080 웹 페이지에 가보자.

- hello 버튼을 클릭하거나 localhost:8080/hello 주소로 이동하면 다음 사진과 같은 페이지로 이동한다.

- 작동원리
- localhost:8080 웹 브라우저에서 hello 버튼을 클릭하거나 주소창에 localhost:8080/hello를 입력하면 웹 브라우저가 내장 톰켓 서버에 localhost:8080/hello를 던진다.
- 톰켓 서버는 /hello 값이 들어온 것을 확인 후 helloController에게 던져준다.
- HelloController 클래스에 있는 @GetMapping("hello")에 매칭되어 메소드가 실행된다.
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello!!");
return "hello";
}
- Spring이 model을 만들어서 전달. model의 data값에 "hello!!"라고 저장.
- return "hello";를 실행하게 되면 Spring은 resources -> templates 폴더 아래에 hello.html가 있는지 찾는다. 있으면 렌더링한다. 이 과정을 thymeleaf 템플릿 엔진이 처리해준다.
- 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버(viewResolver)가 화면을 찾아서 처리한다.
- 스프링 부트 템플릿엔진은 기본 viewName 매핑이 된다.
- 'resources:templates/' + {viewName} + '.html' 파일이 열리게 된다.
<!DOCTYPE HTML>
<html 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>
</body>
</html>
- 위의 코드의 p태그에서 data 값에는 "hello!!"가 적용된다.
프로젝트 빌드해보기
- 지금까지는 인텔리제이 IDE에서 실행했으므로 빌드를 진행한다.
- cmd 창을 열고 프로젝트 파일의 경로를 하나씩 입력

- 빌드가 성공하면 cd build -> cd libs -> ls -arlth -> java -jar hello-spring-0.0.1-SNAPSHOT.jar를 순서대로 입력하면 완료
- 서버를 배포할 때는 hello-spring-0.0.1-SNAPSHOT.jar 이 파일명을 복사해서 서버에 넣어주고 이 파일을 실행시키면 서버에서도 스프링이 동작한다.