[스프링 입문] 정리노트 - 1

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 강의

시작

프로젝트 환경설정


개발환경은 맥북 M1 Pro 입니다.

JAVA 11 설치


기본적으로 Java 17 버전이 설치되어있습니다. ARM64 java 11버전을 다운로드 받고 다음과 같이 버전을 변경해줍니다.

bash
# 설치된 JAVA 확인
/usr/libexec/java_home -V 

# 환경변수를 11버전으로 변경
export JAVA_HOME=$(/usr/libexec/java_home -v 11)

InteliJ 설치


InteliJ는 우선 무료버전인 커뮤니티 버전으로 진행하겠습니다.

스프링 부트 프로젝트 생성


spring initializer

Spring-Web-MVC-capture1

패키지는 Gradle Project가 대중적입니다. 언어는 Java를 설정하고 스프링 부트 버전은 강의상으론 2.3.1이지만 현재 시점 릴리즈된 기준 3.1.1버전을 사용하겠습니다.

프로젝트 메타데이터를 작성하고 디펜던시를 선택해 사용할 라이브러리를 주입합니다. 우선 Spring Web 그리고 Thymeleaf를 사용하겠습니다. 이후 Generate버튼을 눌러 프로젝트를 생성합니다.

Spring-Web-MVC-capture2

이후 인텔리 J를 실행하여 Generate된 zip파일을 풀고 파일 내부에 build.gradle을 오픈합니다.

build.gradle에는 스프링 프로젝트 버전 및 주입된 디펜던시를 볼 수 있습니다.

json
plugins {
	id 'java'
	id 'org.springframework.boot' version '3.1.1'
	id 'io.spring.dependency-management' version '1.1.0'
}

group = 'hello'
version = '0.0.1-SNAPSHOT'

java {
	sourceCompatibility = '17'
}

repositories {
	mavenCentral()
}

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'
}

tasks.named('test') {
	useJUnitPlatform()
}

Spring-Web-MVC-capture3
또한 위 처럼 빌드를 Gradle이 아닌 InteliJ로 변경해주면 좀 더 빠르게 빌드를 수행할 수 있습니다.

사용할 라이브러리


기본적으로 사용할 라이브러리는 다음과 같습니다. 해당 라이브러리는 Spring Web혹은 thymeleaf디펜던시에 주입되어 있습니다.

  • 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: 테스트 프레임워크
    • mockioto: 목 데이터 라이브러리
    • assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리
    • spring-test: 스프링 통합 테스트 지원

GET Started


정적 페이지 생성하기

정적 리소스 파일이 위치한 resources폴더내 static폴더에 index.html파일을 생성해줍니다. 이제 이 페이지가 서버 실행시 메인페이지가 됩니다.

html
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    Hello
    <a href="/hello">hello</a>
</body>
</html>

Spring-Web-MVC-capture4

Controller 구현하기


src/main/java/hello.hellospring/controller/HelloController.class 파일을 생성하여 다음과 같이 컨트롤러를 생성합니다.

java
// HelloController.class
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 view controller 중 Model
        // key : data value : hello
        model.addAttribute("data", "hello!");
        // return 은 hello. viewResolver에 의해
        // resource/templates 폴더내 hello.html파일을 찾아 렌더링한 후 변환해준다.
        // viewResolver는 스프링 부트 템플릿엔진 기본 viewName 매핑 resolver
        // `resources:templates/`+{ViewName}+`.html`과 같은 형식의 파일은 반환한다.
        return "hello";
    }
}

그리고 resources/templates폴더내 hello.html파일을 생성합니다.

html
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p>
</body>
</html>

Spring-Web-MVC-capture5

build 진행하여 jar 파일로 서버 실행하기


이제 빌드를 통해 실행가능한 jar파일을 생성하기 위해 터미널을 열고 프로젝트 경로로 진입하여 다음과 같이 빌드를 진행합니다.

bash
# 빌드
./gradlew build

# jar 파일 경로
# /project/build/libs

이제 다음과 같이 실행하면 서버가 실행됩니다.

bash
java -jar hello-spring-0.0.1-SNAPSHOT.jar

파라미터 받아 화면에 표시하기 MVC와 템플릿 엔진


viewResolver 를 통해 return 내용에 따라 정적 페이지를 렌더링하여 사용자에게 넘겨주는 특징을 이용해 name파라미터를 받아 안녕하세요 [name]을 출력하는 페이지를 만들어봅시다.

우선 api를 새로 만듭니다.

java
@GetMapping("hello-mvc")
    public String helloMvc(@RequestParam(name = "name", required = false) String name, Model model) {
        // @RequestParam(name = "name", required = false) String name
        // required는 default가 true이다. 때문에 api 요청시 반드시 name이 파라미터로 넘어와야한다.
        // command + P로 도움을 얻을 수 있다.
        model.addAttribute("name", name);
        return "hello-template";
    }

그리고 resources/tamplates폴더에 hello-template.html파일을 생성합니다.

html
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<p th:text="'안녕하세요. ' + ${name}">안녕하세요. 손님</p>
</body>
</html>

이제 서버를 실행시키면 다음과 같이 파라미터로 전송된 name이 화면에 출력되는것을 볼 수 있습니다.

Spring-Web-MVC-capture6