[스프링 입문] 2일차 - 라이브러리 살펴보기, View 환경 설정, 빌드하고 실행하기

tdddt·2024년 2월 6일
0

스프링 입문

목록 보기
2/13

라이브러리 살펴보기

💡Gradle은 의존관계가 있는 라이브러리들을 함께 다운로드한다.

폴더에서 살펴보기

  • build.gradle 파일 > dependencies
    • org.springframework.boot:spring-boot-starter-thymeleaf
    • org.springframework.boot:spring-boot-starter-web
    • org.springframework.boot:spring-boot-starter-test
  • External Libraries 폴더
    • 추가하지 않았는데도 들어가 있는 라이브러리들
    • Gradle/Maven 같은 빌드 툴이 의존관계를 관리해 준다. 일례로, spring-boot-starter-web을 추가할 때, 작동에 필요한 tomcat, mvc 등을 자동으로 다운받는다.

라이브러리 의존관계 확인하기

(1) 좌측 하단 클릭해서 우측 바 활성화 > (2) Gradle > (3) hello-spring > Dependencies

  • (*)이라고 표시된 경우는 이미 다운받은 것들이라 중복을 방지하기 위해 표시한 것. 더클 클릭하면 찾아갈 수 있다.
  • 현업에서는 System.out.println을 사용하지 않는다. 대신 로그를 사용하는데, 로그로 남겨야 심각한 에러만 따로 모아보는 등의 로그 파일 관리가 가능함 -> 실무에서는 로그를 쓴다 !

스프링부트 라이브러리

spring-boot-starter-web

  • spring-boot-starter-tomcat : 톰캣(웹서버)
  • spring-webmvc : 스프링 웹 MVC(Model View Controller)

spring-boot-starter-thymeleaf : 템플릿 엔진(View)

spring-boot-starter : 스프링 부트 + 스프링 코어 + 로깅

  • spring-boot
    • spring-core
  • spring-boot-starter-logging
    • slf4j : 인터페이스
    • logback : 실제 로그를 어떤 구현체로 출력할 것인지
    • 요즘은 slf4j, logback의 두 조합을 많이 사용한다.

테스트 라이브러리

spring-boot-starter-test

  • JUnit : 핵심 라이브러리, 테스트 프레임워크 (JUnit5를 많이 쓰는 추세)
  • mockito,assertj : 테스트를 좀 더 편리하게 도와주는 라이브러리
  • spring-test : 스프링 통합 테스트 지원


View 환경 설정

정적 페이지 동작 (Welcome page)

💡 main/resources/static/index.html을 자동으로 welcome page로 인식한다.

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>
  • 스프링부트 : 스프링 생태계를 감싸서 편리하게 사용할 수 있도록 도와 준다.

  • 스프링 : 자바 엔터프라이즈 웹 애플리케이션 개발과 관련된 전반의 생태계를 전부 제공한다. 매우 방대하므로 필요한 걸 찾는 능력이 중요 !!

  • 공식 문서 찾는 법 : spring.io > Projects > Spring Boot > Learn > 버전에 맞는 Reference Doc 확인


thymeleaf 템플릿 엔진 동작

컨트롤러 : 웹 애플리케이션에서의 첫 번째 진입점

main/java/hello.hellospring.controller/HelloControll.java

//controller 패키지 생성 후, 자바 클래스 HelloController 생성

@Controller 
public class HelloController {
    @GetMapping("hello") //웹 어플리케이션에서 /hello라고 들어오면 hello 메소드 호출
    public String hello(Model model) {
        model.addAttribute("data", "hello!!");
        return "hello";
    }
}

main/resources/templates/hello.html

  • xml에 스키바루스 선언 -> thymeleaf 문법 사용 가능
  • p태그 > th에서 ${data}는 HelloController의 hello 메소드,model.addAtrribute부분. key값 data를 입력했으므로, value "hello!!"로 치환돼서 나타남
<!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) 톰캣 : Spring한테 물어보기

3) helloController @GetMapping("hello")
이때, Get은 HTTP Get Method

4) url 매칭, hello 메소드 실행
스프링이 model을 만들어서 알아서 넣어주며, model(data:"hello!!")과 return값을 넘겨준다.

5) 컨트롤러에서 return 값으로 문자를 반환하면 viewResolver가 화면을 찾아서 처리. resources/templates 밑에 있는 viewName을 매핑(템플릿 엔진)
resources/templates/ +{ViewName}+ .html


+) 서버 재시작 없이 View 파일 변경하는법

spring-boot-devtools 라이브러리를 추가하면, html 파일을 컴파일(build > build recompile)만 해주면 서버 재시작없이 View 파일 변경이 가능하다.



빌드하고 실행하기

빌드 후에는 jar 파일만 있으면 실행 가능

터미널 열어서

1) ./gradlew build

2) cd build/libs

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

4) 실행확인(localhost:8080)

./gradle clean : build 폴더를 지워 줌

./gradle clean build : 기존 build폴더를 지우고 완전히 다시 build

0개의 댓글