티스토리 뷰

Web

Thymeleaf 여러 유형 객체 View 바인딩

터프남 2020. 12. 2. 15:58
728x90

Thymeleaf에서 다양한 객체 값 view에 바인딩 예제 정리

객체

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProductVO {
    private String name;
    private int price;
    private Date regDate;
}

 

첫 번째 VO 객체 데이터 view에 데이터 바인딩 방법

model로 보내준 attributeName에 객체 property 명을 붙여주면 출력된다.

@Controller
public class SampleController {

    @GetMapping("/ex01")
    public String ex01(Model model) {
        ProductVO productVO = new ProductVO();
        productVO.setName("상품A");
        productVO.setPrice(10000);
        productVO.setRegDate(new Date());

        model.addAttribute("productVO", productVO);

        return "object_view";
    }
}

Thymeleaf HTML

.을 이용하여 속성 값에 접근한다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head th:replace="./header.html :: fragment-header"></head>
    <body class="container">
        <h1>Thymeleaf 예제</h1>
        <table class="table table-striped">
            <tr>
                <th>이름</th>
                <th>가격</th>
                <th>등록날짜</th>
            </tr>
            <tr>
                <td th:text="${productVO.name}"></td>
                <td th:text="${productVO.price}"></td>
                <td th:text="${productVO.regDate}"></td>
            </tr>
        </table>

    </body>
</html>

두 번째  List<객체> 바인딩

@Controller
public class SampleController {

    @GetMapping("/ex02")
    public String ex02(Model model) {

        List<ProductVO> productList = new ArrayList<>();
        IntStream.range(0, 10).forEach(i -> {
            productList.add(new ProductVO("상품" + i, i * 1000, new Date()));
        });
        model.addAttribute("productList", productList);

        return "list_view";
    }
}

Thymeleaf HTML

model attribute로 넘긴 productList를 가지고 th:each (반복문) 을 사용해서 값을 가져온다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head th:replace="./header.html :: fragment-header"></head>
    <body class="container">
        <h1>Thymeleaf 예제</h1>
        <table class="table table-striped">
            <tr>
                <th>이름</th>
                <th>가격</th>
                <th>등록날짜</th>
            </tr>
            <tr th:each="list : ${productList}">
                <td th:text="${list.name}"></td>
                <td th:text="${list.price}"></td>
                <td th:text="${list.regDate}"></td>
            </tr>
        </table>

    </body>
</html>

세 번째 Map<Key, Value> 객체

@Controller
public class SampleController {

    @GetMapping("/ex03")
    public String ex03(Model model) {

        Map<String, Object> map = new HashMap<>();
        map.put("key1", 100);
        map.put("key2", 200);
        map.put("key3", 300);

        model.addAttribute("mapList", map);

        return "map_view";
    }
}

Thymeleaf HTML

th:each로 반복하는 것은 같지만 Map을 attribute로 보냈을 때는 key로 value를 가지고 올 수 있다.

그런데 자바에서 Map은 순서를 보장하지 않기 때문에 순서를 보장받으려면 LinkedHashMap을 사용하면 된다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head th:replace="./header.html :: fragment-header"></head>
    <body class="container">
        <h1>Thymeleaf 예제</h1>
        <table class="table table-striped">
            <tr>
                <th>이름</th>
                <th>가격</th>
            </tr>
            <tr th:each="entry : ${mapList}">
                <td th:text="${entry.key}"></td>
                <td th:text="${entry.value}"></td>
            </tr>

        </table>

    </body>
</html>

네 번째 Map<Key, List> 형식

@Controller
public class SampleController {

    @GetMapping("/ex04")
    public String ex04(Model model) {

        Map<String, List<ProductVO>> map = new HashMap<>();

        List<ProductVO> productList = new ArrayList<>();
        List<ProductVO> productList2 = new ArrayList<>();

        IntStream.range(0, 10).forEach(i -> {
            productList.add(new ProductVO("상품" + i, i * 1000, new Date()));
        });
        IntStream.range(0, 10).forEach(i -> {
            productList2.add(new ProductVO("상품2" + i, i * 100, new Date()));
        });

        map.put("key1", productList);
        map.put("key2", productList2);

        model.addAttribute("mapList", map);

        return "map_list_view";
    }
}

Thymeleaf HTML

이런 형식은 가끔씩 쓰이기도 하는데 key의 value에 List가 들어있으니 value를 th:each로 뽑아낸다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head th:replace="./header.html :: fragment-header"></head>
    <body class="container">
        <h1>Thymeleaf 예제</h1>
        <table class="table table-striped">
            <tr>
                <th>No</th>
                <th>이름</th>
                <th>List</th>
            </tr>
            <tr th:each="entry : ${mapList}">
                <td th:text="${entryStat.count}"></td>
                <td th:text="${entry.key}"></td>
                <td>
                    <table class="table">
                        <tr th:each="list : ${entry.value}">
                            <td th:text="${list.name}"></td>
                            <td th:text="${list.price}"></td>
                            <td th:text="${list.regDate}"></td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </body>
</html>

다섯 번째  List<Map>

@Controller
public class SampleController {

    @GetMapping("/ex05")
    public String ex05(Model model) {

        List<Map<String, ProductVO>> mapList = new ArrayList<>();

        Map<String, ProductVO> fakeData = new LinkedHashMap<>();
        fakeData.put("testA", new ProductVO("상품A", 10000, new Date()));
        fakeData.put("testB", new ProductVO("상품B", 5000, new Date()));
        fakeData.put("testC", new ProductVO("상품C", 1000, new Date()));
        mapList.add(fakeData);
        fakeData.clear();
        fakeData.put("testA", new ProductVO("상품A", 10000, new Date()));
        fakeData.put("testB", new ProductVO("상품B", 5000, new Date()));
        fakeData.put("testC", new ProductVO("상품C", 1000, new Date()));

        mapList.add(fakeData);

        model.addAttribute("mapList", mapList);

        return "list_map_view";
    }
}

Thymeleaf HTML

List<Map> 객체 바인딩

실제로 이렇게 쓸 일이 있는지는 모르겠지만 어쨌든 올려본다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head th:replace="./header.html :: fragment-header"></head>
    <body class="container">
        <h1>Thymeleaf 예제</h1>
        <h3 th:text="${mapList}"></h3>
        <table class="table table-striped">
            <tr>
                <th>No</th>
                <th>이름</th>
                <th>가격</th>
                <th>날짜</th>
            </tr>
            <tr th:each="list : ${mapList}">
                <td th:text="${listStat.count}"></td>
                <td th:text="${list.testA.name}"></td>
                <td th:text="${list.testA.price}"></td>
                <td th:text="${list.testA.regDate}"></td>
            </tr>
        </table>
    </body>
</html>

 

모든 소스코드

https://github.com/sskim91/java-spring-lab/tree/main/sample-thymeleaf

 

sskim91/java-spring-lab

Contribute to sskim91/java-spring-lab development by creating an account on GitHub.

github.com

참고

https://bit.ly/3mIatQ1

 

How to loop through Map in Thymeleaf

I am trying to understand how to loop through all entries in a Map in Thymeleaf. I have a domain object being processed by Thymeleaf that contains a Map. How do I loop through the keys and fetch ...

stackoverflow.com

 
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/06   »
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
글 보관함