Notice
Recent Posts
Recent Comments
Link
«   2024/03   »
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
Archives
Today
Total
관리 메뉴

공부하자

[Spring Boot] 5. 타임리프 (2) 본문

공부/Spring Boot

[Spring Boot] 5. 타임리프 (2)

strongstar 2017. 12. 1. 02:02

* 참고 도서 : 쇼다 츠야노 (2017). 스프링 부트 프로그래밍 입문. 길벗

* 가급적 자주, 적어도 일주일에 한번 이상은 포스팅하려고 합니다.

* 이전 포스팅 : [Spring Boot] 4. 타임리프 (1)



1. 조건, 분기, 반복문


- TestController.java


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
package com.star.springboot;
 
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class TestController {
    
    @RequestMapping("/{num}")
    public ModelAndView index(@PathVariable int num, ModelAndView mav) {
        mav.setViewName("index");
        
        mav.addObject("num", num);
        mav.addObject("check", num % 2 == 0);
        mav.addObject("trueVal""Even number.");
        mav.addObject("falseVal""Odd number.");
        
        ArrayList<String[]> list = new ArrayList<String[]> ();
        list.add(new String[] {"kim""kim@a.com"});
        list.add(new String[] {"lee""lee@b.com"});
        mav.addObject("list", list);
                
        return mav;
    }
    
}
 
cs


- index.html


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
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
</head>
<body>
    <h1>Hello</h1>
    
    <!-- "변수식 ? 값1 : 값2" -->
    <p th:text="${num} + ' : ' + (${check} ? ${trueVal} : ${falseVal})"></p>
    
    <!-- if -->
    <p th:if="${check}" th:text="${num} + ' : ' + ${trueVal}">true</p>
    <p th:unless="${check}" th:text="${num} + ' : ' + ${falseVal}">false</p>
    
    <!-- switch -->
    <div th:switch="${num}">
        <p th:case="1" th:text="one">1</p>
        <p th:case="2" th:text="two">2</p>
        <p th:case="3" th:text="three">3</p>
        <p th:case="*">?</p>
    </div>
    
    <!-- each -->
    <table border="1">
        <tr>
            <td>NAME</td>
            <td>E-MAIL</td>
        </tr>
        <tr th:each="obj:${list}">
            <td th:text="${obj[0]}"></td>
            <td th:text="${obj[1]}"></td>
        </tr>
    </table>
 
</body>
</html>
cs


- 실행 결과






여러 예제를 하나로 묶으니 편하네요. 진작 이렇게 할걸..


다음글에서는 전처리, 인라인 처리, 템플릿 프래그먼트에 대해 다루도록 하겠습니다.

거기까지 하면 타임리프는 끝날 것 같네요.


Comments