본문 바로가기
기초 및 언어/▶ Spring

01. Spring_기초, 출력하기

by 류딩이 2025. 9. 18.

1. Spring Boot main()

Spring Boot 프로젝트를 실행할 때 main() 메서드를 가진 클래스 하나만 실행 

 

실행 (main) 파일위치

src > main > java > com.example.Ex02(Ex01Application 파일)

package com.example.Ex02;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Ex01Application {

    public static void main(String[] args) {
        SpringApplication.run(Ex01Application.class, args);
        System.out.println("시작");
    }
}
SpringApplication.run(Ex01Application.class, args);


Ex01Application.class → 실행의 기준 클래스 (패키지 스캔, 설정 시작점) , args → 실행 옵션(외부 파라미터) 전달
👉 “Ex01Application을 기준으로 스프링 부트를 실행하고, 실행 인자(args)도 적용해라”라는 뜻


 

2. Spring Boot 출력방법

🔽간단 출력 

System.out.println()

 

 

3. Spring Boot + Thymeleaf Controller 정리

Spring Boot에서 **컨트롤러(Controller)**는 클라이언트의 요청을 받아서 처리하고, 뷰(HTML 템플릿)로 데이터를 전달하는 역할

 

 

🔽  전체코드

더보기
더보기
package com.example.Ex02.controller;

import com.example.Ex02.dto.ItemDto;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value="/thymeleaf") // 요청명 앞에 항상 /thymeleaf가 붙게 만듬
public class ThymeleafController {

    @RequestMapping(value = "/ex01", method = RequestMethod.GET)
    public String Exam01(Model model){
        model.addAttribute("name","아이유");
        model.addAttribute("age",30);
        model.addAttribute("addr", "서울");
        return "view01"; // resources/templates/~~/html
    }
    // @RequestMapping(value= "/ex02", method = RequestMethod.GET)
    @GetMapping(value = "/ex02")
    public String Exam02(Model model){
        ItemDto itemDto = new ItemDto();
        itemDto.setNo(1);
        itemDto.setItemNm("상품");
        itemDto.setItemDetail("상품 설명");
        itemDto.setPrice(3000);
        model.addAttribute("itemDto",itemDto);
        return "view02";
    }

    @GetMapping("/ex03")
    public String Ex03(Model model){
        List<ItemDto> lists = new ArrayList<ItemDto>();
        for(int i=1; i<10; i++){
            ItemDto itemDto = new ItemDto();
            itemDto.setNo(1);
            itemDto.setItemNm("상품");
            itemDto.setItemDetail("상품 설명");
            itemDto.setPrice(3000);
            lists.add(itemDto);

        }
        model.addAttribute("lists",lists);

        return "view03";
    }

    // http://localhost:9292/thymeleaf/ex04
    @GetMapping("/ex04")
    public String Ex04(Model model){
        return "thymeleaf/view04";
    }


    // http://localhost:9292/thymeleaf/ex05
    // http://localhost:9292/thymeleaf/ex05?param1=가나&param2=다라
    // 주소지에 매개변수 정확히 일치하기
    @GetMapping("/ex05")
    public String Ex05(Model model, String param1, String param2){
        if(param1 == null){
            param1 ="하하하";
        }
        if(param2 == null){
            param2 = "호호호";
        }

        model.addAttribute("param1", param1);
        model.addAttribute("param2", param2);
        return "thymeleaf/view05";
    }


}

폴더안에 있다면

return "폴더/파일명";

 

 

0 클래스 레벨 매핑

@Controller
@RequestMapping(value="/thymeleaf") // 요청명 앞에 항상 /thymeleaf가 붙게 만듬

 

  • @Controller : 이 클래스가 컨트롤러임을 명시
  • @RequestMapping("/thymeleaf") : 이 클래스 안의 모든 요청 URL 앞에는 /thymeleaf가 붙음

👉  /thymeleaf/ex01, /thymeleaf/ex02 처럼 접근


1. 단일 값 전달 (/ex01)

// http://localhost:9292/thymeleaf/ex01
@RequestMapping(value = "/ex01", method = RequestMethod.GET)
public String Exam01(Model model) // (Model, 임시변수)
	model.addAttribute("name", "아이유")
    model.addAtrribute("age", 30)
    model.addAtrribute("addr", "서울")
    return "view01";

 

  • Model 객체에 데이터 저장 (addAttribute)
  • 뷰 파일: resources/templates/view01.html
  • 화면에서 ${name}, ${age}, ${addr}로 출력 가능
<body>
view01.html

name1: <p th:text="${name}"></p>
name2: [[${name}]] <br>

age1 : <p th:text="${age}"></p>
age2: [[${age}]] <br>

addr1 : <p th:text="${addr}"></p>
arrr2 : [[${addr}]] <br>
</body>

2. 객체 전달 (/ex02)

@GetMapping(value = "/ex02")
public String Exam02(Model model){
    ItemDto itemDto = new ItemDto();
    itemDto.setNo(1);
    itemDto.setItemNm("상품");
    itemDto.setItemDetail("상품 설명");
    itemDto.setPrice(3000);
    model.addAttribute("itemDto",itemDto);
    return "view02";   
}

 

  • ItemDto 객체 생성 후 set으로 값을 넣음
<body>
    view02.html
    번호1: <span th:text="${itemDto.no}"></span> <br>
    번호2: [[${itemDto.no}]] <br>
    번호3: <span th:text="${itemDto.getNo()}"></span> <br>
    번호4: [[${itemDto.getNo()}]] <br>

    상품설명1 : <span th:text="${itemDto.itemDetail}"></span>
    상품설명2 : [[${itemDto.itemDetail}]]
    상품설명3: <span th:text="${itemDto.getItemDetail()}"></span> <br>
    상품설명4 : [[${itemDto.getItemDetail}]]

    가격1 :<span th:text="${itemDto.price}"></span>
    가격2 : [[${itemDto.price}]]
    가격3 :[[${itemDto.getPrice()}]]


</body>

3. 리스트(List) 전달 (/ex03)

 

 @GetMapping("/ex03")
    public String Ex03(Model model){
        List<ItemDto> lists = new ArrayList<ItemDto>();
        for(int i=1; i<10; i++){
            ItemDto itemDto = new ItemDto();
            itemDto.setNo(1);
            itemDto.setItemNm("상품");
            itemDto.setItemDetail("상품 설명");
            itemDto.setPrice(3000);
            lists.add(itemDto);

        }
        model.addAttribute("lists",lists);

        return "view03";
    }

 

  • List<ItemDto> 형태로 여러 개의 객체를 담아 뷰로 전달
  • 뷰에서는 th:each 반복문을 통해 출력 가능
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    view03.html<br>

    <table border="1">
            <tr>
                <th>상태값</th>
                <th>번호</th>
                <th>상품명</th>
                <th>셜명</th>
                <th>가격</th>
            </tr>

<!--        th:each = "변수, 상태변수:컬렉션"-->
<!--        th:each = "변수 : 컬렉션"-->
<!--        for(하나:컬렉션)-->
            <tr th:each="itemDto : ${lists}">
            <td th:text="${itemDtoStat.count}"></td>
            <td th:text="${itemDto.no}"></td>
            <td th:text="${itemDto.itemNm}"></td>
            <td th:text="${itemDto.itemDetail}"></td>
            <td th:text="${itemDto.price}"></td>
        </tr>
    </table>
<br><br>
<div th:each="num : ${#numbers.sequence(1,5,2)}">
    <p th:text="${num}"></p>
    <p th:text="${'index:' + numStat.index}"></p>
    <p th:text="${'count' + numStat.count}"></p>
    <p th:text="${'first' + numStat.first}"></p>
    <p th:text="${'last' + numStat.last}"></p>
    <p th:text="${'size' + numStat.size}"></p>
    <hr>
</div>
</body>
</html>

 

✅1. Thymeleaf 반복문(th:each)과 상태변수 사용법

 

  • th:each="itemDto : ${lists}"
    → 컨트롤러에서 model.addAttribute("lists", list객체)로 넘긴 리스트를 하나씩 꺼내와서 itemDto라는 이름으로 사용
  • ${itemDto.no}, ${itemDto.itemNm} …
    → 객체의 필드를 출력
  • 상태변수: ${itemDtoStat.count}
    → th:each는 자동으로 변수명 + Stat 이라는 상태변수를 제공합니다.

2. 상태변수 종류

th:each="변수, 상태변수 : ${리스트}"

 

형태로 쓰면 상태변수를 직접 이름 붙여 사용
하지만 이름을 안 붙여도 기본적으로 ${변수명Stat} 으로 접근 가능

  • index → 0부터 시작하는 인덱스
  • count → 1부터 시작하는 순번
  • size → 전체 크기
  • even / odd → 짝수/홀수 여부 (true/false)
  • first → 첫 번째 원소 여부 (true/false)
  • last → 마지막 원소 여부 (true/false)

 

📌 설명

  • #numbers.sequence(1,5,2)
    → 1부터 5까지 2씩 증가 (결과: 1, 3, 5)
  • num → 현재 반복 중인 값
  • numStat → 반복 상태변수
num = 1, index=0, count=1, first=true, last=false, size=3
num = 3, index=1, count=2, first=false, last=false, size=3
num = 5, index=2, count=3, first=false, last=true, size=3

 

 

✅ 정리

  • th:each → 리스트나 배열 반복
  • 상태변수(변수명Stat)를 통해 인덱스, 카운트, 첫/마지막 여부 확인 가능
  • #numbers.sequence(start, end, step) → 숫자 반복문 지원

5. 단순 뷰 호출 (/ex04)

 

/ http://localhost:9292/thymeleaf/ex04
@GetMapping("/ex04")
public String Ex04(Model model){
    return "thymeleaf/view04";
}

 

<a href="/thymeleaf/ex01">예제 1로 이동</a><br>
<a th:href="@{/thymeleaf/ex01}">예제 1로 이동</a><br>
<a th:href="@{http://www.thymeleaf.org}">타임리프 페이지로 이동</a><br>

<a th:href="@{/thymeleaf/ex05}">예제 5로 이동</a><br>
<a th:href="@{/thymeleaf/ex05(param1='abc', param2='xyz')}">예제 5로 param1, param2를 가지고 이동</a><br>

✅ 정리

  • HTML href : 문자열 그대로 사용
  • th:href="@{/...}" : 컨텍스트 경로 자동 인식 (권장)
  • th:href="@{/url(param1='값', param2='값')}" : GET 방식 파라미터 자동 추가
  • th:href="@{http://외부주소}" : 외부 사이트 이동

5. 파라미터 받기 (/ex05)

    // http://localhost:9292/thymeleaf/ex05
    // http://localhost:9292/thymeleaf/ex05?param1=가나&param2=다라
    // 주소지에 매개변수 정확히 일치하기
    @GetMapping("/ex05")
    public String Ex05(Model model, String param1, String param2){
        if(param1 == null){
            param1 ="하하하";
        }
        if(param2 == null){
            param2 = "호호호";
        }
        model.addAttribute("param1", param1);
        model.addAttribute("param2", param2);
        return "thymeleaf/view05";
    }
}
param1 : <span th:text="${param1}"></span><br>
param2 : <span th:text="${param2}"></span><br>

 

param을 가지고 Ex04에서 출력하면 param값이 출력되고

가지고가지 않으면 하하하, 호호호 출력