4 min read

<Spring> 스프링 프로젝트 시작하기

해당 글은 김영한님의 <스프링 입문> 강좌를 기반으로 작성되었습니다.

프로젝트 생성

  • 준비물 : Java 11, IDE(인텔리제이 사용)
  • https://start.spring.io/에 들어가서 의존성 설정
  • Project : Gradle 선택(구글링 해봐도 메이븐보다 그레이들이 낫다고 한다)
  • Springboot : 2.3.x
  • Language : java
  • Packaging : jar
  • Java : 11
  • groupId : hello
  • artifact : hello-sing
  • Dependancies : SpringWeb, TyhmeLeaf
  • 위의 사항으로 설정하고 generate 선택하면 zip 파일이 생성됩니다.
  • 이후 해당 파일 압축해제하고 inteliJ에서 프로젝트 open하면, 처음 build하면 시간이 좀 걸린 후, Application을 실행해서 whiteLabel 에러 페이지가 나오면 완성입니다.
  • 그레이들은 아래 코드를 수행하면서, 서로 의존성을 가지는 모든 라이브러리들을 해당 프로젝트에 끌어옵니다.
plugins {
	id 'org.springframework.boot' version '2.3.12.RELEASE'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'
}

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

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') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

View 환경설정

Welcome Page 생성
  • 경로 : resources/static/index.html
<!DOCTYPE HTML>
<html lang="ko">
    <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 생성하기
  • 위의 그림의 디렉토리 구조처럼 아래의 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 {

    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data","spring!");
        return "hello";
    }
}

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" lang="ko">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>
  • @GetMapping("hello") : get요청이 hello로 들어오면 hello메소드를 호출하여서 hello.html파일을 리턴하게하는 어노테이션이다.
  • hello.html 파일의 경우 thymeLeaf를 사용해서 웹 페이지를 띄우고 있다.
  • $data는 model의 data로 넘어가는 key값이고, “spring!” 이라는 value를 웹페이지에서 리턴한다.
스프링부트 동작 환경 그림
  • Controller에서 리턴 값으로 문자를 반환하면, view-resolver 가 해당 문자열의 이름을 갖는 html파일을 찾아서 서버를 거쳐 브라우져에 띄운다.
  • 스프링에서 view-resolver가 html을 찾는 기본 경로는 resources/templates이다.
  • 그림을 보면 스프링 부트는 내장 톰캣 서버를 가지고 있기 때문에 따로 WAS가 필요하지 않고, JAR파일로 배포가 가능하다.

빌드하고 실행하기

  • 8080 포트가 중복되는 에러가 발생하기 때문에 IDE에서 실행중인 프로젝트는 무조건 중단하고 진행해야 합니다.
  • 터미널에서 현재위치를 해당 프로젝트가 있는 경로로 이동한다.
  • 이후 , ./gradlew build
  • cd bulid/libs
  • java -jar hello-spring-0.0.1-SNAPSHOT.jar
  • 순으로 실행하면 아래 화면처럼 실행된다.