본 프로젝트는 “스프링부트 3 백엔드 개발자 되기” 서적을 참고하여 진행하였음
타임리프
•
타임리프는 템플릿 엔진이다.
◦
템플릿 엔진: 스프링 서버에서 데이터를 받아 우리가 보는 웹 페이지, 즉 HTML 상에 그 데이터를 넣어 보여주는 도구이다.
•
문법
표현식 | 설명 |
${…} | 변수의 값 표현식 |
#{…} | 속성 파일 값 표현식 |
@{…} | URL 표현식 |
*{…} | 선택한 변수의 표현식. th:object에서 선택한 객체에 접근 |
th:text | 텍스트를 표현할 때 사용 - th:text=${person.name} |
th:each | 컬렉션을 반복할 때 사용 - th:each=”person:${persons}” |
th:if | 조건이 true인 때만 표시 - th:if=”${person.age} ≥ 20” |
th:unless | 조건이 false인 때만 표시 - th:unless=”${person.age}≥20” |
th:href | 이동 경로 - th:href=”@{/person(id=${person.id})}” |
th:with | 변수값으로 지정 - th:with=”name = ${person.name}” |
th:object | 선택한 객체로 지정 - th:object=”${person}” |
<h1 text=${이름}>
<p text=${나이}>
JavaScript
복사
•
타임리프 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf:2.7.16'
Java
복사
•
타임리프 문법 익히기용 컨트롤러 작성
◦
모델(Model) 객체는 뷰, 즉, HTML 쪽으로 값을 넘겨주는 객체이다.
◦
모델 객체는 따로 생성할 필요 없이 코드처럼 인자로 선언하기만 하면 스프링이 알아서 만들어주므로 편리하게 사용할 수 있다.
package com.example.msblog.controller;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDate;
import java.util.List;
@Controller
public class ExampleController {
@GetMapping("/thymeleaf/example")
public String thymeleafExample(Model model) { // 뷰로 데이터를 넘겨주는 모델 객체
Person examplePerson = new Person();
examplePerson.setId(1L);
examplePerson.setName("홍길동");
examplePerson.setAge(11);
examplePerson.setHobbies(List.of("운동", "독서"));
model.addAttribute("person", examplePerson); // Person 객체 지정
model.addAttribute("today", LocalDate.now());
return "example";
}
@Getter
@Setter
class Person {
private Long id;
private String name;
private int age;
private List<String> hobbies;
}
}
Java
복사