1. properties 환경 설정 방법
Spring Boot에서는 application.properties 또는 application.yml 파일을 사용하여 애플리케이션의 설정을
관리한다. 이 파일들은 주로 src/main/resources 디렉토리에 위치한다.
💡 주요 설정 방법
- 키-값 쌍으로 설정 정의
- 프로필별 설정 파일 사용
(ex : application-dev.properties) - 외부 설정 파일 사용
💡 주요 설정 항목
설정 항목 | 설명 | 예시 |
server.port | 서버 포트 설정 | server.port=8080 |
spring.datasource.url | 데이터베이스 URL | spring.datasource.url= jdbc:mysql://localhost/mydb |
logging.level | 로깅 레벨 설정 | logging.level.root=INFO |
💻 application.properties 예시 코드
server.port=8080
spring.datasource.url=jdbc:mysql://localhost/mydb
spring.datasource.username=user
spring.datasource.password=password
logging.level.org.springframework.web=DEBUG
2. application.properties, application.yml 차이
application.properties와 application.yml는 모두 Spring Boot 애플리케이션의 설정을 관리하는 파일이지만,
구조와 문법에 차이가 있다.
📌 주요 차이점
특성 | application.properties | application.yml |
문법 | 키-값 쌍 | YAML 형식 |
구조 | 평면적 | 계층적 |
가독성 | 단순한 설정에 적합 | 복잡한 설정에 더 적합 |
들여쓰기 | 사용하지 않음 | 중요 (공백으로 계층 표현) |
💻 application.properties, application.yml 문법 예시 코드
spring.datasource.url=jdbc:mysql://localhost/mydb
spring.datasource.username=user
spring.datasource.password=password
spring:
datasource:
url: jdbc:mysql://localhost/mydb
username: user
password: password
[Spring Boot] application.properties와 application.yml의 차이점
목차 개요 Spring Boot 프로젝트에서는 일반적으로 프로젝트의 각종 설정을 application.properties 또는 application.yml 파일을 통해 하게된다. 기본적으로 Spring Initializr를 통해 Spring Boot 프로젝트를 생성하
colabear754.tistory.com
- 참고 : colabear754
3. Thymeleaf 이해하기
서버 사이드 템플릿 엔진으로, Spring Framework에서 공식적으로 지원하는 Template engine이다.
💡 주요 특징과 개념
1️⃣ Template Engine의 개념
- 프로그램 로직과 프레젠테이션 계층을 분리하기 위한 수단이다.
- 프레젠테이션 계층에서 로직을 쉽게 표현하고, 개발의 유연성을 향상시키며 유지보수의 효율 또한 향상된다.
- Controller에서 View로 데이터를 보내면 데이터를 View에서 볼 수 있게 도와준다.
2️⃣ 서버 지원 Template Engine
- 서버 템플릿 엔진(SSR: Server Side Rendering)
서블릿(서버)에서 동작하는 템플릿 - 템플릿 엔진이 데이터를 이용해 HTML을 생성하여 브라우저에 전달한다.
- 정적인 템플릿 양식과 데이터가 매핑되어 HTML 문서를 만들어주는 SW를 그 종류로 다양하다.
3️⃣ Thymeleaf의 특징
- Spring Framework에서 공식적으로 지원하는 템플릿 엔진
- Spring 진영에서 적극적으로 지원
- HTML을 그대로 유지하면서 뷰 템플릿 기능을 사용할 수 있음 (Natural Templates)
- 서버 사이드 렌더링(SSR)을 지원
4️⃣ Thymeleaf vs 다른 템플릿 엔진
- JSP
서버 사이드에서 동작, Java 코드를 직접 삽입 가능, 스프링 부트에서는 권장하지 않는다. - Mustache
로직 코드를 사용할 수 없어 View 역할과 서버의 역할을 명확히 분리,
클라이언트/서버 템플릿으로 모두 사용 가능하다. - FreeMarker
대부분의 경우 HTML을 생성하는 데 필요한 모든 기능을 갖추고 있으나 배우기가 더 쉽다는 평가를 받는다.
5️⃣ Thymeleaf의 장점
- Natural Templates
HTML을 그대로 유지하면서 추가 기능을 사용할 수 있어 디자이너와의 협업이 용이하다. - Spring 통합
Spring Framework와의 통합이 잘 되어 있어 사용이 편리하다. - 다양한 기능
조건문, 반복문, 변수 등 다양한 템플릿 기능을 제공한다. - 확장성
사용자 정의 방언(dialect)을 통해 기능 확장이 가능하다.
🚀 Template engine이란?
프로그램 로직을 표현하는 계층과 서비스를 사용하는 유저가 보는 데이터 출력을 위한 프레젠테이션 계층을
분리하기 위한 수단으로, Controller에서 View로 데이터를 보내면 데이터를 View에서 볼 수 있게 도와준다.
mustache, thymeleaf 등이 spring을 개발하는 프로그래머들이 선호하는 template로 알려져 있다.
📌 JSP, Mustache, Thymeleaf, FreeMarker 비교
JSP | 서버 지원 템플릿 엔진으로 서버에서 구동한다. 서버에서 Java 코드로 출력자료를 만든 뒤 이 문자열을 HTML 형식으로 변환해 브라우저로 전달한다. 스프링부트에서는 WAS에 종속적인 JSP를 더 이상 권장하지 않고 있다. |
Mustache | 스프링부트에서 공식으로 지원하는 템플릿 엔진으로 Java는 물론, 현존하는 대부분의 언어를 지원한다. 1. JSP와 같이 HTML을 만들어주는 템플릿 엔진 2. 로직 코드를 사용할 수 없어 View 역할과 서버의 역활을 명확히 분리한다. 3. Mustache.js와 Mustache.java를 사용해 하나의 문법으로 클라이언트/서버 템플릿으로 모두 사용 가능하다. |
Thymeleaf | 스트링 부트에서 공식으로 지원하는 템플릿 엔진이다. 스프링 진영에서 적극적으로 지원한다. |
FreeMarker | 스프링부트에서 공식으로 지원하는 템플릿 엔진이다. 대부분의 경우 HTML을 생성하는 데 필요한 모든 필수 기능을 갖추고 있으며 배우기가 더 쉽다. 그러나 템플릿에 사용자 지정 기능을 추가하려는 경우 Thymeleaf를 사용하는 것이 효과적으로 알려져 있다. |
🚀 각 Template engine의 빌드 크기
애플리케이션 배포와 관련하여 크기가 중요하다. 작은 빌드는 CI 플랫폼 간에 프로덕션 서버로 이전하기가 더 편하다.
환경에 차이가 있을 수 있으나 일반적으로 빌드된 JAR 파일 크기를 비교해 본 결과는 아래와 같다.
Mustache가 약 16MB의 용량을 가진 확실한 승자이며 Thymeleaf가 그 뒤를 잇고 있다.
FreeMarker는 Thymeleaf보다 뒤처지지 않았지만 Groovy는 21.4MB 크기로 훨씬 뒤처졌다.
🚀 애플리케이션 부팅 시간
이 그래프는 스트링 부트 애플리케이션의 각 변형에 대한 시작 시간을 보여준다.
서로 다른 템플릿 엔진 간의 간격은 약 1초에 불과하지만 실제 차이는 훨씬 더 클 것이다.
💻 Thymeleaf application.properties기본값
spring.application.name=sprweb06_Th
server.port=80
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=. html
spring.thymeleaf.encoding=UTF-8
💻 Thymeleaf 설정 예시 코드 (Spring Boot)
@Configuration
public class ThymeleafConfig {
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(thymeleafTemplateResolver());
return templateEngine;
}
@Bean
public SpringResourceTemplateResolver thymeleafTemplateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
return templateResolver;
}
}
Thymeleaf 이해하기
HTML : compile 없이 클라이언트 쪽 브라우저에서 해석(파싱)해 바로 출력해 준다.자바스크립트 : 브라우저 위에서 구동하므로 서버 템플릿 엔진의 손을 벗어나 제어할 수 없다. ** Template engine이란
cafe.daum.net
- 출처 : 데이터 과학자 + 프로그래머 세상 다음카페
FreeMarker vs Groovy vs Mustache vs Thymeleaf
In this post, we will try to compare FreeMarker vs Groovy vs Mustache vs Thymeleaf with examples. Spring Boot supports FreeMarker, Groovy, Mustache and
springhow.com
- 참고 : springhow.com
4. Thymeleaf 기본 문법과 활용 방법
Thymeleaf는 HTML 태그에 특별한 속성을 추가하여 동적 콘텐츠를 생성한다.
📌 주요 문법
문법 | 설명 | 예시 |
th:text | 텍스트 출력 | <p th:text="${message}">Hello</p> |
th:each | 반복문 | <li th:each="item : ${items}" th:text="${item}">Item</li> |
th:if th:unless |
조건문 | <p th:if="${condition}">Shown if true</p> |
th:href | 링크 생성 | <a th:href="@{/user/{id}(id=${user.id})}">User</a> |
th:object th:field |
폼 바인징 | <form th:object="${user}"><input th:field="*{name}"/></form> |
💻 활용 예시 코드
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User List</title>
</head>
<body>
<h1 th:text="${title}">Default Title</h1>
<ul>
<li th:each="user : ${users}" th:text="${user.name}">User name</li>
</ul>
</body>
</html>
Thymeleaf 기본 문법과 활용 방법
Thymeleaf에서 자주 사용하는 문법. 대부분의 html 속성을 th:예약어 로 변경할 수 있다. html lang=en xmlns:th=http://www.thymeleaf.org : 타임리프의 th 속성을 사용하기 위해 선언된 네임스페이스
cafe.daum.net
- 출처 : 데이터 과학자 + 프로그래머 세상 다음카페
5. JSP와 Thymeleaf 차이
JSP와 Thymeleaf는 모두 서버 사이드 템플릿 엔진이지만, 몇 가지 중요한 차이점이 있다.
💡 주요 차이점
특성 | JSP | Thymeleaf |
문법 | Java 중심 코드 | HTML 속성 기반 |
템플릿 | JSP 전용 문법 | 순수 HTML |
학습 곡선 | 가파름 (Java 지식 필요) |
상대적으로 완만 |
성능 | 컴파일 필요 | 인터프리터 방식 |
Spring Boot 지원 | 제한적 | 우수 |
💻 예시 비교 (JSP, Thymeleaf)
<c:forEach var="user" items="${users}">
<p>${user.name}</p>
</c:forEach>
<p th:each="user : ${users}" th:text="${user.name}"></p>
[Spring]JSP vs Thymeleaf
자바 프로그래밍을 처음 배울 때 기본적으로 JSP를 배운다. JSP는 일반적인 Java MVC 구조에서 View의 역할을 하는데 요즘 Spring에서는 View로 Thymeleaf를 더 추구한다고 한다! JSP vs Thymeleaf JSP의 경우에는
velog.io
- 참고 : posasac.log
[Spring] Thymeleaf(타임리프)란? Thymeleaf(타임리프)와 JSP 차이점은 뭘까?
Spring Boot Thymeleaf Thymeleaf란 ? Thymeleaf (타임리프)는 controller가 전달하는 데이터를 이용해 동적으로 화면을 만들어주는 역활을 view templates 엔진 서버상에서 동작하지 않아도 HTML 파일의 내용을 바로
h0-0cat.tistory.com
- 참고 : h0-0cat
6. Redirectattributes
RedirectAttributes는 Spring MVC에서 리다이렉트 시 데이터를 전달하는 데 사용되는 인터페이스이다.
💡 주요 특징
- Flash 속성을 사용하여 리다이렉트 후 한 번만 사용 가능한 데이터 전달
- URL 파라미터로 데이터 전달 가능
📌 주요 메소드
메소드 | 설명 |
addFlashAttribute() | Flash 속성 추가 |
addAttribute() | URL 파라미터로 속성 추가 |
💻 예시 코드
@PostMapping("/user")
public String createUser(@ModelAttribute User user, RedirectAttributes redirectAttributes) {
userService.save(user);
redirectAttributes.addFlashAttribute("message", "User created successfully");
redirectAttributes.addAttribute("id", user.getId());
return "redirect:/user/{id}";
}
@GetMapping("/user/{id}")
public String showUser(@PathVariable Long id, Model model,
@ModelAttribute("message") String message) {
model.addAttribute("user", userService.findById(id));
return "user";
}
'에이콘아카데미 회고 > 5회차) 자바기반 풀스택 개발자 양성과정' 카테고리의 다른 글
Spring, Spring Boot) 62번째 회고 (0) | 2024.07.17 |
---|---|
Spring, Spring Boot) 61번째 회고 (0) | 2024.07.16 |
Spring, Spring Boot) 59번째 회고 (0) | 2024.07.12 |
Spring, Spring Boot) 58번째 회고 (0) | 2024.07.10 |
Spring, Spring Boot) 57번째 회고 (0) | 2024.07.09 |