Web_Backend/Spring

[스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 - 인프런] 1. 프로젝트 생성

Carnival7 2021. 1. 10. 22:21

1. 프로젝트 생성

  • options : Gradle / Java11 / Spring Boot 2.3.x / Spring Boot web, Thymelaf

2. 라이브러리

스프링 부트 라이브러리

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

3. View 환경설정

  • welcome page
    static/index.html 을 올려두면 Welcome page 기능을 제공한다.
    static폴더의 index.html을 찾아 맨 처음 /(루트) view(Welcome Page)로 지정하며, static 폴더에 못찾을 경우 template 폴더까지 스캔 한다. 만약 둘다 없다면 자동적으로 애플리케이션 welcome page를 사용한다.

thymeleaf template

컨트롤러 : java/hello.hellospring/controller/HelloController.java

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!!");
        // resources/templates/hello.html 에 data로 "hello!!"라는 string값을 보낸다.
        return "hello"; // resources/templates 에서 'hello'라는 이름을 가진 html 파일을 찾아가 렌더링해라.
    }

}

뷰 :

1. resources/static/index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

2. resources/template/hello.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p>
<!--HelloController로부터 data("hello!!")를 받아 사용한다.-->
</body>
</html>

thymeleaf 템플릿엔진 동작 확인

컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버(viewResolver)가 화면을 찾아서 처리한다.

  • 스프링 부트 템플릿엔진 기본 viewName 매핑
  • resources:templates/ + {ViewName} + .html

4. 빌드하고 실행

  1. 콘솔로 이동
  2. gradlew.bat build d build/libs
  3. java -jar hello-spring-0.0.1-SNAPSHOT.jar
  4. 실행 확인