[SpringBoot-스프링 입문] 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술: 1. 프로젝트 환경설정
해당 강의는 Inflearn에 등록된 김영한님의 Springboot 강의입니다.
0. Intelli J(인텔리 제이) 단축키 모음 (윈도우 사용자)
Ctrl
+/
-> 주석 처리 및 주석 해제Alt
+enter
-> 임포트 추가 및 함수 생성 등 대부분 빨간 줄 해결- 그냥 코드에 sout 입력+
tab
->System.out.println(); Shift
+F6
->클릭한 변수와 다른 변수들의 이름이 같으면 해당 변수들의 이름을 한번에 편집가능.Ctrl
+alt
+v
->선택한 코드 블록을 변수로 추출하는 단축키
Ctrl
+alt
+m
-> 선택한 코드 블록을 메소드로 추출하는 단축키
Ctrl
+alt
+p
-> 메서드 호출시 매개변수 자동생성 단축키임Ctrl
+alt
+l
-> Reformat Code. 즉, 코드를 예쁘게 꾸며 줌.Ctrl
+n
-> 클래스 검색Ctrl
+shift
-> 한컴입력기 or microsoft 입력기
(한글 깔려 있는 사람들 주석 처리 안되면 microsoft입력기로 입력)Fn
+alt
+insert
-> generate 키
(getter,setter,생성자, equals(), hashCode()등등 유용한 코드 블럭들을 사용 가능)
Ctrl
+shift
+T
=> 생성한 repository에서
테스트 케이스 작성 단축키
1. 프로젝트 설정(Spring Boot 3.xx 버전)
1. IntelliJ IDE 다운로드 및 JDK-17 설치
IntelliJ IDE 다운로드: https://www.jetbrains.com/ko-kr/idea/
JDK-17 다운로드 : https://www.oracle.com/kr/java/technologies/downloads/
위와 같이 다운로드 완료시 성공.
+a)학생이면 인텔리제이 유료 버전을 무료로 사용 가능합니다.
2. https://start.spring.io/ 방문
3. 2번 설정 후 Generate 하면 hello-spring.zip 파일 생성
4. zip파일 압축 해제후 build.gradle 더블클릭(IntelliJ IDE로 열기)
5. Group,Artifact,Package가 제대로 생성되었음으로 확인.
6. build.gradle 설정 (추후에 쓸 라이브러리들의 설명은 주석처리하였습니다! )
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
//★★★자바가 DB와 연동하기 위해선 jdbc 드라이버가 필요하다.
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
//★★★data-jpa: ★★jpa 드라이버+jdbc드라이버 포함이다.
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
//데이터베이스의 클라이언트 (추후 데이터 베이스 설치시 사용)
//runtimeOnly 'com.h2database:h2'
}
tasks.named('test') {
useJUnitPlatform()
}
7. 설치한 JDK 적용 및 build run 설정
최근 IntelliJ 버전은 Gradle을 통해서 실행 하는 것이 기본 설정입니다.
다음과 같이 변경하면 Gradle을 안통하고, IntelliJ 내장 빌드 시스템에서 바로 실행해서 실행속도가 훨씬 더 빠릅니다.
8. 기본 메인 클래스 실행 및 localhost:8080 이동(localghost: 실행 컴퓨터 ,8080: 포트 번호)
✨ 기능 별 코드의 디렉토리 위치는 다음과 같습니다. ✨
자바코드: /src/main/java/hello/hellospring/
html(View)코드: /src/main/resources/
테스트 코드: /src/test/java/hello/hellospring/
위와 같이 whitelabel 로 뜨면 정상적으로 서버가 작동한 것 입니다.
9. View 환경설정
Welcome Page만들기
resources/static
에 index.html 을 올려두면 해당 view(html)을 Welcome page로 작동. 이는SpringBoot
가 제공하는 기능이다.
<!--static/index.html 을 올려두면 Welcome page 기능을 제공한다.-->
<!DOCTYPE HTML>
<html>
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<a href="/hello-caps">hello-caps</a>
</body>
</html>
10. thymeleaf 템플릿 엔진 사용
1. MVC(모델-뷰-콘트롤러) 설정
controller
및model
설정
java/hello/hellospring/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 {
// 1. mvc(파라미터가 없는 경우)
// "/hello-changuk" 값이 입력되면 "hello"라는 뷰이름을 반환함.
// 추후, "hello.html"을 뷰 리졸버가 찾아 템플릿엔진이
// SSR(서버사이드 랜더링)을 한다.
@GetMapping("/hello-caps")
public String hello(Model model) {
//model은 data라는 키값과 changuk!!이라는 내용으로 구성되어 있다.
model.addAttribute("data", "CAPS!!");
return "hello"; //ctrl+click은 해당 소스로 넘어감.
}
}
view
설정
resources/templates/hello.html
<!DOCTYPE HTML>
<!--thymeleaf라서 th이다.-->
<!--thymeleaf는 hmtl 템플릿 엔진(View)이다.-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!--model의 키값: data-->
<!--view resolver가 화면을 찾아서 처리-> resources:templates/ +ViewName.html-->
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>
결과
11. 템플릿 엔진 동작 과정
위 hello메서드
는 http
의 Get
요청을 응답한다.
다음의 코드를 보자
@Getmapping("경로") String 메서드명(Model model)
{
model.addAttribute("키","값"); //모델(키,값) 설정
return "VIEWname"
}
url의 경로 값이 입력되면 model
을 setting하고, hello라는 뷰 이름
을 반환함. 이후 뷰에서는 model
의 키
인 data
를 통해 처리hello.html("view명.html")
을 뷰 리졸버
가 찾아 템플릿엔진
이SSR
(서버사이드 랜더링)을 한다. 그 반대는 CSR
(클라이언트 사이드 랜더링)이라 한다. CSR
이란 서버에서는 API
만 만들고, 클라이언트는 이 API를 호출하여 받은 데이터
를 기반으로한다. 클라이언트 측에서는 각 프레임워크
(ex:리액트)에 따라 동적으로 UI(view)
를 구성하여 랜더링 작업
을 한다.