개발천재

[Spring Boot] Thymeleat를 이용한 구구단 만들기 본문

개발 준비/Spring Boot

[Spring Boot] Thymeleat를 이용한 구구단 만들기

세리블리 2025. 2. 10. 23:16
반응형
[ 초기 설정 ]
- controller Package 폴더 생성 후 GuguController 생성
- templates에 gugu.html 생성

 

 

Controller에서 GetMapping 작업하기

model.addAttribute("range", 9); → 1부터 9까지 반복할 수 있도록 range 값을 전달한다.
반환값 "gugu" → gugu.html 템플릿을 렌더링한다.

package com.example.testMvc.controller;

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

@Controller
public class TestController {
    @GetMapping("/gugudan")
    public String gugudan(Model model) {
        model.addAttribute("range", 9);
        return "/gugu";
    }
}

 

 

gugu.html 작업하기

#numbers.sequence(2, 9) → 2단부터 9단까지 반복한다.

#numbers.sequence(1, range) → 각 단에서 1부터 9까지 반복한다.
th:block을 사용하여 th:each 내부에서 <p>를 그룹화한다.

 

Thymeleaf에서 th:each는 Java의 for-each 반복문과 같은 역할을 한다.

<!DOCTYPE html>
<html lang="en" xmlns:th="http:www.thymeleaf.com">
<head>
    <meta charset="UTF-8">
    <title>Gugudan</title>
</head>
<body>
<h1>Gugudan</h1>
    <th:block th:each="i : ${#numbers.sequence(2, 9)}">
    <p th:text="|${i}단|"></p>
        <th:block th:each="j : ${#numbers.sequence(1, range)}">
            <p th:text="|${i} x ${j} = ${i*j}|"></p>
        </th:block>
    </th:block>
</body>
</html>

 

#numbers.sequence(시작, 끝)
#numbers.sequence(2, 9)는 2부터 9까지의 숫자를 생성하는 역할을 한다.
즉, [2, 3, 4, 5, 6, 7, 8, 9]와 같은 리스트가 만들어진다.

 

 

#numbers.sequence(시작, 끝, step)
숫자 간격을 조정하고 싶다면 세 번째 인자(step) 를 추가할 수도 있다. 아래와 같이 step에 2가 들어가면 숫자 2만큼 간격이 생겨 1, 3, 5, 7, 9 가 출력된다.

<ul>
    <li th:each="num : ${#numbers.sequence(1, 10, 2)}" th:text="${num}"></li>
</ul>

 

 

#numbers.array(2, 3, 9)

특정 단수만 출력할 경우에는 #numbers.array 사용한다.

<th:block th:each="i : ${#numbers.array(2, 3, 9)}">
    <p th:text="|${i}단|"></p>
    <th:block th:each="j : ${#numbers.sequence(1, range)}">
        <p th:text="|${i} x ${j} = ${i * j}|"></p>
    </th:block>
</th:block>
반응형