language: Java 11
IDE: IntelliJ
Gradle-Groovy Project/Java/2.7.9
Group은 기업domain명(hello), Artifact가 프로젝트명(hello-spring), Name/Description/Package name은 유지
Dependencies는 사용할 라이브러리(spring web:웹프로젝트만들것, thymeleaf:HTML템플릿엔진)
version을 2.7.9 보다 큰 verison으로 하면 error 발생
=> version이 3 이상이면 Java 17을 사용하는 것이 유리
압축파일 푼 폴더 -> hello-spring -> build.gradle 오픈
open as project
9번째 줄 실행 후 localhost:8080 url 검색 결과
💡 Spring boot application을 실행하면, spring boot가 tomcat 웹서버를 내장하고 있어 자체적으로 tomcat 위에 spring boot 실행됨
Preferences > gradle 검색 > build and run using과 Run tests using을 둘 다 IntelliJ IDEA로 설정
파일에 설치된 라이브러리와 관련된 모든 라이브러리를 보여줌
Gradle
: 의존관계(dependencies)가 있는 모든 라이브러리를 다운로드
: 타임리프 템플릿 엔진(view)
: 스프링 부트 + 스프링 코어 + 로깅
1. spring-boot
=> spring-core
2. spring-boot-starter-logging
=> logback, slf4j
src/main/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>
💡 welcome page
: domain만 누르고 들어왔을 때 보이는 첫 화면
💡 앞의 Welcome page는 정적 페이지, 템플릿 엔진을 이용해 형태를 바꿀 수 있음
package
생성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") // url로 검색했을 때 localhost:8080/hello 일 경우 아래 함수 실행
public String hello(Model model) { // model 생성
model.addAttribute("data", "hello!!"); // key값은 data, 해당 값은 hello!!
return "hello"; // resources/templates 아래에 존재하는 "hello.html" 실행
}
}
// 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>
💡 spring-boot-devtools
라이브러리
html 파일을 컴파일만 해주면 서버 재시작 없이 view 파일 변경 가능 (컴파일 방법: build -> Recompile)
💎 설치1) build.gradle에 코드의 dependencies에 코드 추가
implementation 'org.springframework.boot:spring-boot-devtools'
💎 설치 2) 프로젝트 닫은 후 File -> Open -> 해당 프로젝트의 build.gradle을 선택. 그 다음 Open as Project를 선택
thymeleaf 공식 사이트 https://www.thymeleaf.org/
💡 intelliJ 실행 중 빌드할 수 없음. localhost:8080은 한 번에 하나만 가능
💡 cmd 에서 빌드
cd C:\spring_study
cd hello-spring
gradlew
gradlew build
cd build
cd libs
cd dir
java -jar hello-spring-0.0.1-SNAPSHOT.jar
ctrl+c 또는 ctrl+z로 종료
💡 server 배포할 때 빌드한 파일만 복사해서 server에 넣어주고 java -jar (파일이름) 실행
🔜 server에서 spring 동작
[출처] 김영한_스프링입문