본문 바로가기
Backend/Spring

스프링 - 프로젝트 생성 및 템플릿 엔진 사용하기

by 퐁고 2023. 2. 25.
반응형

스프링 부트 시작

  • 요즘은 Maven에서 Gradle로 프로젝트 사용을 한다.
  • 스프링 부트에서
    • SNAPSHOT - 만들고 있는 버전
    • M1 - 정식 릴리즈된 버전이 아님
  • Group - 기업 도메인 명을 적어줌
  • Artifact - 결과물 (프로젝트명)
  • Dependencies
    • 내가 프로젝트에 어떤 라이브러리를 쓸거냐
      • Spring Web
      • thymeleaf - html 만들어주는 템플릿 엔진
      • GENERATE 누르기 (다운)
  • 압축을 풀고 인텔리제이에서 열기
    • build.gradle로 열기

프로젝트 구조

  • src
    • main
      • java, resources
    • test - 테스트 파일
  • build.gradle - 설정 파일
    • 스프링 부트 생성 에러가 난다면 아래 링크 들어가기
 

스프링 3.0.2 프로젝트 생성 에러 발생

Spring Initializr를 이용하여 Spring Boot 3.0.2 프로젝트를 생성하던 도중 다음과 같은 에러가 발생했다.A problem occurred configuring root project 'java-test-practice'.Could not res

velog.io

  • 자바 실행을 빠르게 하기 위해서는 설정에서 gradle로 바꿈
    • build and run - Gradle → IntelliJ
    • run tests using - Gradle → IntelliJ
  • Annotation Processors → Enable annotation processing (체크) → lombook 사용

스프링 부트 라이브러리

  • 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: 테스트 프레임워크, 요즘 5버전
  • mockito: 목 라이브러리
  • assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리
  • spring-test: 스프링 통합 테스트 지원

View 설정

 

Spring Boot Features

Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest

docs.spring.io

hello.hellospring 패키지 → controller 패키지 생성 → HelloController 클래스 생성

// HelloController

@Controller
public class HelloController {
 @GetMapping("hello")
 public String hello(Model model) {
 model.addAttribute("data", "hello!!");
 return "hello";
 }
}
// 컨트롤러에서 리턴값으로 문자를 반환하면 viewResolver가 화면을 찾아 처리한다. return이 hello이므로
// templates/hello.html에 hello라는 html 파일을 찾는다. -> resource:templates/{ViewName}.html

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>
// ${data}는 Controller에서 addAttribute("data","hello!!");로 했기 때문에 안녕하세요. hello!!로 출력
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

댓글