[스프링 입문] Section 1. 프로젝트 환경설정

본 포스팅의 내용은

인프런 김영한님의 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 강의 기반으로 작성했습니다.

 

✍️ 프로젝트 선택

Project: Gradle Project

Spring Boot: 2.6.8

Language:

Java Packaging: Jar

Java: 11

 

Gradle 설정

plugins {
   id 'org.springframework.boot' version '2.6.8'
   id 'io.spring.dependency-management' version '1.0.11.RELEASE'
   id 'java'
}

group = 'com.kangworld'
version = '0.0.1-SNAPSHOT'
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'
    
	testCompileOnly 'org.projectlombok:lombok:1.18.24'
	testAnnotationProcessor 'org.projectlombok:lombok:1.18.24'
}

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

 

라이브러리 살펴보기

spring-boot-starter-web

 spring-boot-starter-tomcat: 톰캣 (웹서버)

 spring-webmvc: 스프링 웹 MVC

 spring-boot-starter-thymeleaf: 타임리프 템플릿 엔진(View)

 spring-boot-starter(공통): 스프링 부트 + 스프링 코어 + 로깅

 

spring-boot-starter-test

 junit: 테스트 프레임워크

 mockito: 목 라이브러리

 assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리

 spring-test: 스프링 통합 테스트 지원

 

🖥️ View 환경 설정

Welcome Page 만들기

static/index.html을 만들면 Spring boot가 제공하는 Welcome page 기능을 제공한다.

 

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>

 

@Controller 생성

웹 브라우저에서 /hello로 요청이 들어오면 아래 hello 메서드를 호출함

@Controller
public class HelloController {
    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data", "hello!!");

        return "hello";
    }
    
    ```
}

 

resources/templates/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>

 

웹브라우저에서 /hello라고 던지면 스프링 부트가 내장한 톰캣 서버에서 /hello를 받는다.

이후 톰캣은 /hello 요청을 Spring에 전달한다. Spring은 Controller에서 hello에 매핑되는 메서드를 찾고 존재한다면 해당 메서드를 실행한다.

 

매핑 메서드에선 Model에 key 값은 "data" attribute는"hello!!"를 저장하고 문자열 "hello"를 반환하고 resources/templates에서 hello에 매핑된 hello.html을 렌더링 하라고 지시한다. 조금 더 디테일하게 설명하면 컨트롤러에서 리턴 값으로 문자열을 반환하면 viewResolver가 html을 찾아서 렌더링 한다.