Updated:

프로젝트 생성

 스프링 부트 스타터 사이트로 이동해서 스프링 프로젝트를 생성한다. src/main/java/hello.hellospring의 HelloSpringApplication을 실행하면 localhost::8080에서 실행이 된다.

package hello.hellospring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloSpringApplication {

	public static void main(String[] args) {
		SpringApplication.run(HelloSpringApplication.class, args);
	}

}

라이브러리 살펴보기

 스프링 부트 라이브러리는 다음과 같다.

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

View 환경설정

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>

static/index.html을 올려두면 스프링 부트가 제공하는 Welcome Page 기능을 제공한다.

thymeleaf 템플릿 엔진

src/main/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!!");
        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.html에서 ${data}를 HelloController.java의 model.addAttribute(“data”, “hello!!”);를 통해 hello!!로 치환해 준다. 즉, helloController는 return: hello와 model(data:hello!!)를 가지고 있어 templates 패키지에서 hello.html을 찾은 뒤 data를 hello!!로 변환해 주는 것이다.
build.gradle의 dependencies에 developmentOnly ‘org.springframework.boot:spring-boot-devtools’을 추가해주면 서버 재시작 없이 View 파일 변경이 가능하다.

빌드하고 실행하기

 터미널을 Command Prompt로 실행하고 gradlew.bat를 입력한 뒤 gradlew build로 실행한다. 이후 libs로 이동한 후 java -jar hello-spring-0-0.1-SNAPSHOT.jar을 실행한다.

댓글남기기