참치코더의 꿈 메모장

Spring / Thymeleaf 기본 문법 간단 미니 정리 본문

Spring

Spring / Thymeleaf 기본 문법 간단 미니 정리

참치깡 2026. 1. 2. 13:28
728x90

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@Controller
@RequestMapping("/basic")
public class BasicController {
 
    @GetMapping("text-basic")
    public String textBasic(Model model){
        model.addAttribute("data""Hello Spring!");
        return "basic/text-basic";
    }
 
    @GetMapping("text-unescaped")
    public String textUnescaped(Model model){
        model.addAttribute("data""Hello <b>Spring!</b>");
        return "basic/text-unescaped";
    }
 
    @GetMapping("/variable")
    public String variable(Model model){
        User userA = new User("userA"10);
        User userB = new User("userB"20);
 
        List<User> list = new ArrayList<>();
        list.add(userA);
        list.add(userB);
 
        Map<String, User> map = new HashMap<>();
        map.put("userA", userA);
        map.put("userB", userB);
 
        model.addAttribute("user", userA);
        model.addAttribute("users", list);
        model.addAttribute("userMap", map);
 
        return "basic/variable";
    }
 
    @Data
    static class User {
        private String username;
        private int age;
 
        public User(String username, int age){
            this.username = username;
            this.age = age;
        }
    }
}
cs

 

 

th:text : 텍스트 출력 (HTML 이스케이프)

 

<span th:text="${data}"></span>

 

- 모델에 담긴 값을 출력

- HTML태그는  이스케이프 처리됨

 

예시

data = "Hello <b>Spring!</b>"

 

출력 결과

Hello <b>Spring!</b>

 

- XSS 공격 방지를 위해 기본적으로 안전한 방식

 

[[...]]  : 인라인 텍스트 출력

 

[[${data}]]

 

- th:text와 동일한 역할

- HTML 이스케이프 처리됨

- 태그 안에서 간단히 값 출력할 때 유용

 

th:utext : HTML 그대로 출력

 

<span th:utext="${data}"></span>

 

- HTML 태그를 그대로 해석

- 보안에 취약, 신뢰 가능한 데이터만 사용

 

Hello <b>Spring!</b>  // Spring! 이 굵게 표시됨

 

[(...)] : 인라인 비이스케이프 출력

 

[(${data})]

 

- th:utext와 동일

- HTML 태그를 그대로 렌더링

 

th:inline="none" : 타입리프 파싱 방지

 

<span th:inline="none">[[...]]</span>

 

- [[...]], [(...)] 같은 문법을 문자 그대로 출력

- 문법 설명용 예제에서 자주 사용

 

SpringEL 표현식

 

Thymeleaf는 Spring Expression Language(SpEL)를 사용한다.

 

객체(Object) 접근

 

<span th:text="${user.username}"></span>

<span th:text="${user['username']}"></span>

<span th:text="${user.getUsername()}"></span>

 

- 세 가지 모두 동일한 결과로 출력된다.

 

리스트(List) 접근

 

<span th:text="${users[0].username}"></span>

<span th:text="${users[0]['username']}"></span>

<span th:text="${users[0].getUsername()}"></span>

 

- 인덱스로 접근

- 객체 접근 방식은 동일

 

맵(Map) 접근

 

<span th:text="${userMap['userA'].username}"></span>

<span th:text="${userMap['userA']['username']}"></span>

<span th:text="${userMap['userA'].getUsername()}"></span>

 

- ['key'] 방식으로 Map 값 접근

 

 

728x90
Comments