Spring Boot | Thymeleaf 엔진 사용 | 반복 출력


코드 작성

src/main/java/sample/springboot/web/HelloController.java

package sample.springboot.web;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping(method=RequestMethod.GET)
    public String hello(Model model) {
        List<Hoge> list = Arrays.asList(
                            new Hoge() {{
                                id = 10;
                                value = "hoge";
                            }},
                            new Hoge() {{
                                id = 20;
                                value = "fuga";
                            }},
                            new Hoge() {{
                                id = 30;
                                value = "piyo";
                            }});

        model.addAttribute("hogeList", list);

        return "hello";
    }
}

src/main/resources/templates/hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8" />
    <title>Hello Thymeleaf</title>
  </head>
  <body>
    <dl th:each="hoge : ${hogeList}">
      <dt>id</dt>
      <dd th:text="${hoge.id}"></dd>

      <dt>value</dt>
      <dd th:text="${hoge.value}"></dd>
    </dl>
  </body>
</html>

설명

  • th:each으로 지정된 컬렉션을 반복할 수 있다.