반복

알파로그·2023년 3월 24일
0

Spring MVC 활용 기술

목록 보기
12/42

✏️ 반복문 사용하기

📍 Controller 계층

   @GetMapping("/each")
    public String each(Model model) {
        addUsers(model);
        return "basic/each";
    }

    // model 을 매개변수로 받아 여러 mapping method 에서 호출해 사용될 수 있다.
    private void addUsers(Model model) {
        List<User> list = new ArrayList<>();
        list.add(new User("UserA", 10));
        list.add(new User("UserB", 20));
        list.add(new User("UserC", 30));

        model.addAttribute("users", list);
    }

📍 table + 반복문 기본 사용방법

  • HTML table
    • tr = row
    • th = column name (meta 정보)
    • td = data
  • each
    • th:each=”index : Collection
    • td 에 해당하는 부분이 반복의 대상이 될 수 있게 구현 해준다.
<h1>기본 테이블</h1>
<table>

    <tr>
        <th>username</th>
        <th>age</th>
    </tr>

    <tr th:each="user : ${users}">
        <td th:text="${user.username}">username</td>
        <td th:text="${user.age}">0</td>
    </tr>

</table>

✏️ Collection 속성

📍 특징

  • Collection 의 다양한 속성을 확인할 수 있음
  • 사용 방법
    • th:each=”index, stat : Collection"
    • index = Collection 의 각 인자를 뜻하는 변수
    • stat = Collection 의 속성정보를 담고있는 변수

⚠️ 보통 Collection 의 변수명에 s 가 붙는데,

index 변수는 s 를 제거하고,

stat 은 생략이 될경우 stat 을 변수명으로 사용 가능하다.

<tr th:each="user, userStat : ${users}">

<tr th:each="user : ${users}"> // stat 으로 userStat 처럼 사용 가능

📍 Stat method

  • 현재 index 번호 + 1 출력
<span th:text="${userStat.count}"></span>
  • 현재 index 번호 출력
<span th:text="${userStat.index}"></span>
  • Collection 의 size 출력
<span th:text="${userStat.size}"></span>
  • 현재 index 의 홀, 짝 유무
<span th:text="${userStat.even}"></span> // 홀 == true
<span th:text="${userStat.odd}"></span> // 짝 == true
  • 현재 index 가 첫번째 인지 마지막인지 boolean 으로 출력
<span th:text="${userStat.first}"></span>
<span th:text="${userStat.last}"></span>
profile
잘못된 내용 PR 환영

0개의 댓글