<스프링입문>01. 프로젝트 환경 설정

박서연·2023년 1월 25일
0

Spring

목록 보기
1/10

📌 개발환경

language: Java 11
IDE: IntelliJ

📌 스프링 프로젝트 생성

1. 스프링 부트 스타터 사이트로 이동해서 스프링 프로젝트 생성

https://start.spring.io

Gradle-Groovy Project/Java/2.7.9
Group은 기업domain명(hello), Artifact가 프로젝트명(hello-spring), Name/Description/Package name은 유지
Dependencies는 사용할 라이브러리(spring web:웹프로젝트만들것, thymeleaf:HTML템플릿엔진)

version을 2.7.9 보다 큰 verison으로 하면 error 발생
=> version이 3 이상이면 Java 17을 사용하는 것이 유리

2. 압축풀고 IntelliJ에서 Open or Import

압축파일 푼 폴더 -> hello-spring -> build.gradle 오픈
open as project

3. 코드 run


9번째 줄 실행 후 localhost:8080 url 검색 결과

💡 Spring boot application을 실행하면, spring boot가 tomcat 웹서버를 내장하고 있어 자체적으로 tomcat 위에 spring boot 실행됨

4. build가 gradle 통해 실행될 경우, IntelliJ로 실행되도록 변경

Preferences > gradle 검색 > build and run using과 Run tests using을 둘 다 IntelliJ IDEA로 설정

📌 라이브러리 살펴보기

1. Dependencies

파일에 설치된 라이브러리와 관련된 모든 라이브러리를 보여줌
Gradle
: 의존관계(dependencies)가 있는 모든 라이브러리를 다운로드

2. Spring boot library

1. spring-boot-starter-web

  1. spring-boot-starter-tomcat
    : 톰캣(웹서버)
  2. spring-webmve
    : 스프링 웹 MVC

2. spring-boot-starter-thymeleaf

: 타임리프 템플릿 엔진(view)

3. spring-boot-starter(공통)

: 스프링 부트 + 스프링 코어 + 로깅
1. spring-boot
=> spring-core
2. spring-boot-starter-logging
=> logback, slf4j

3. Test library

spring-boot-starter-test

  1. junit
    : 테스트 프레임워크, 요즘 junit5 사용
  2. mockito
    : 목 라이브러리
  3. assertj
    : 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리
  4. spring-test
    : 스프링 통합 테스트 지원

📌 View 환경설정

1. Welcome Page 만들기

src/main/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>

💡 welcome page
: domain만 누르고 들어왔을 때 보이는 첫 화면

2. Thymeleaf 템플릿 엔진

💡 앞의 Welcome page는 정적 페이지, 템플릿 엔진을 이용해 형태를 바꿀 수 있음

1. 코드 작성

  1. java/hello.hellospring 아래에 controller라는 이름의 package 생성
    controller 아래에 HelloController라는 이름의 Java class 생성
// 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")    // url로 검색했을 때 localhost:8080/hello 일 경우 아래 함수 실행
    public String hello(Model model) {      // model 생성
        model.addAttribute("data", "hello!!");  // key값은 data, 해당 값은 hello!! 
        return "hello";     // resources/templates 아래에 존재하는 "hello.html" 실행
    }
}
  1. resources/templates 아래에 hello.html 생성
// 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>
  1. 실행
    브라우저에 localhost:8080/hello 검색

2. 템플릿엔진 동작

  1. 웹 브라우저에 localhost:8080/hello 검색
  2. 내장 톰캣 서버에서 helloController 실행
    🔸 @GetMapping("hello") // url로 검색했을 때 localhost:8080/hello 일 경우 아래 함수 실행
    🔸 model.addAttribute("data", "hello!!"); // key값은 data, 해당 값은 hello!!
    🔸 return "hello"; // resources/templates 아래에 존재하는 "hello.html" 실행
  3. controller에서 return 값으로 문자를 반환하면 viewResolver가 해당 화면을 찾아 처리
    🔸 스프링 부트 템플릿엔진 기본 viewName(return값)과 매핑
    🔸 resources/templates/ + {viewName} + .html

💡 spring-boot-devtools 라이브러리
html 파일을 컴파일만 해주면 서버 재시작 없이 view 파일 변경 가능 (컴파일 방법: build -> Recompile)
💎 설치1) build.gradle에 코드의 dependencies에 코드 추가

implementation 'org.springframework.boot:spring-boot-devtools'

💎 설치 2) 프로젝트 닫은 후 File -> Open -> 해당 프로젝트의 build.gradle을 선택. 그 다음 Open as Project를 선택

thymeleaf 공식 사이트 https://www.thymeleaf.org/

📌 빌드하고 실행하기

💡 intelliJ 실행 중 빌드할 수 없음. localhost:8080은 한 번에 하나만 가능

1. 빌드

💡 cmd 에서 빌드

cd C:\spring_study
cd hello-spring
gradlew
gradlew build

cd build
cd libs
cd dir

2. Java로 실행

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

ctrl+c 또는 ctrl+z로 종료

💡 server 배포할 때 빌드한 파일만 복사해서 server에 넣어주고 java -jar (파일이름) 실행
🔜 server에서 spring 동작

[출처] 김영한_스프링입문

0개의 댓글