본문 바로가기
Spring

Thymeleaf 기본 문법

by Mecodata 2023. 5. 8.

Thymeleaf

- Java 템플릿 엔진 => html 태그에 속성을 추가해 페이지에 동적으로 값을 추가하거나 처리하게 해줌

- Spring Boot에서 사용하도록 권장되는 템플릿 엔진 (Spring Security 사용 시에 필수!)

템플릿 엔진(Template Engine) = HTML과 데이터를 결합한 결과물(페이지)를 생성해주는 소프트웨어 라이브러리

- Spring Boot는 Thymeleaf로 사용할 html 파일의 경로 기본값 resources/templates로 지정되어 있음

// application.property 버전
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

// application.yml 버전
thymeleaf:
    prefix : classpath:templates/
    suffix : .html

- html 이외의 CSS, JavaScript, 이미지 등의 리소스들의 경로 기본값은 resource/static

- html 태그에 속성(th:)을 추가해 페이지에 동적으로 값을 추가하거나 처리할 수 있음

- Thymeleaf를 적용하기 위해서는 html 파일 내에 다음과 같이 html 태그 입력

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

기본 문법

- 기본적으로 속성 입력시 {}을 활용하여 입력해야 함

- th:text="${}" => 전달받은 데이터 

- th:href="@{}" => URL 주소 설정 (<a>에서 사용)
- th:with="${}" => 변수 형태의 값을 재정의
- th:value="${}" => value에 값을 삽입(<input>에서 사용, 여러 개의 값을 넣는 경우 + 사용)
- th:block = 타임리프 표현을 어느 곳에서든 사용할 수 있도록 설정
- th:fragment=""
- th:if="${}", th:unless="${}"

 

- th:text="${greeting}"

- th:text="${user.firtstName}"

- th:if="${user.isAdmin}" => user.isAdmin이 true인 경우에만 출력에 포함 (조건문)

- th:each="item : $"{items}" th:text="${item}" => items에 있는 각각의 item에 대하여 반복문을 돌려 출력

sec:authentication

- 태그에 대한 접근 권한 설정하는 속성

- hasRole() = 지정한 권한이 있을 경우 출력
- hasAnyRole() = 지정한 권한들 중에서 하나라도 있을 경우 출력
- isAuthenticated() = 권한에 관계없이 로그인 인증을 받은 경우 출력
- isFullyAuthenticated() = 권한에 관계없이 인증에 성공했고 자동 로그인이 비활성인 경우 출력
- isAnonymous() = 권한이 없는 익명의 사용자일 경우 출력
- isRememberMe() = 자동 로그인을 사용하는 경우 출력

- permitAll() = 모든 경우 출력
- denyAll() = 모든 경우 출력 X

- principal 변수를 통해 authentication 객체 안에 있는 UserDetails 객체에 접근 가능 

 

'Spring' 카테고리의 다른 글

의존성 주입 방식  (0) 2023.05.25
JWT  (0) 2023.05.25
Spring Security 기본 로그인 구현 중 실수 정리  (0) 2023.05.11
Spring Security 기본 세팅  (0) 2023.05.09
Spring Security 정의 및 동작 구조  (0) 2023.05.04

댓글