Spring, View 환경 설정 | thymeleaf 템플릿 동작 과정

심삼진·2023년 5월 2일
0

Spring

목록 보기
1/12
post-thumbnail

인프런 강의를 통해 친구들과 Spring 스터디를 하기로 했습니다.

먼저 실습을 하기 위해서 아래와 같은 환경을 만들어야 합니다.

  1. JDK 11 설치
  2. IDE: IntelliJ 또는 Eclipse 설치

저는 IntelliJ Community로 진행하였습니다.

https://start.spring.io

위 사이트를 통해 프로젝트 생성 후 다운받아 IntelliJ에서 열었습니다.



main 메소드를 실행시키면 정상적으로 작동됩니다.



Gradle을 통하지 않고 바로 결과를 확인하기 위해 setting에 들어가 설정해주었습니다.




라이브러리

Gradle은 의존관계가 있는 라이브러리를 함께 다운로드 합니다.

Spring Boot 라이브러리

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 환경 설정

- Spring Boot에서 제공하는 Welcome Page 기능

static/index.html 을 올려두면 Welcome page 기능을 제공합니다.

index.html에 hello가 출력되게끔 간단한 코드를 작성합니다.

<!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>



http://localhost:8080/

서버를 멈추고 다시 실행해주면 에러 페이지에서 welcome page로 바뀝니다.



Reference : https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-welcome-page




thymeleaf 템플릿 엔진



controller 패키지를 만들어서 HelloController 클래스를, templates 폴더에 hello.html을 생성합니다.


< HelloController 코드 >

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

< 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>

그런 다음 http://localhost:8080/hello 로 접속하면 다음과 같이 결과가 나옵니다.




attributeValue 값이 html의 ${data}에 치환되기 때문입니다.





동작 환경 그림

컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버( viewResolver )가 화면을 찾아서 처리합니다.
ㄴ 스프링 부트 템플릿엔진 기본 viewName 매핑
ㄴ resources:templates/ +{ViewName}+ .html

◆ 참고: spring-boot-devtools 라이브러리를 추가하면, html 파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경이 가능합니다.

인텔리J 컴파일 방법: 메뉴 build Recompile


Reference :
thymeleaf 공식 사이트: https://www.thymeleaf.org/
스프링 공식 튜토리얼: https://spring.io/guides/gs/serving-web-content/
스프링부트 메뉴얼: https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-template-engines





빌드하고 실행하기


콘솔 이동

./gradlew build
cd build/libs
java -jar hello-spring-0.0.1-SNAPSHOT.jar
실행 확인


윈도우 유저 Tip

콘솔 ➡️ 이동 명령 프롬프트(cmd)로 이동
./gradlew ➡️ gradlew.bat 를 실행
명령 프롬프트에서 gradlew.bat 를 실행하려면 gradlew 하고 엔터
gradlew build
폴더 목록 확인 ls ➡️ dir





학습중인 스프링 강의 : https://inf.run/pcut
스프링 실습 코드 저장소 : https://github.com/0pyaq0/Spring_Study.git



본 글은 2022년도에 작성한 기존 티스토리 블로그 글을 재업로드한 글입니다
기존 티스토리 블로그 : https://develop-about-leejin.tistory.com/

profile
주니어 백엔드 개발자

0개의 댓글