SPRING

[Spring Boot] html에 데이터 넣기 타임리프 반복문 th:each / LomBok의 @ToString

_-_-kk 2025. 3. 15. 19:06

css 파일은 static 폴더에 넣으면 됨

 static 폴더 파일들은 root경로에 추가되기때문에  경로를 /부터 시작하면 사용가능 

    <link href=" /main.css" rel="stylesheet">
</head>

 

 

 

items 라는 이름으로 result 변수 보내서 html에서 뽑기 

 

List<Item> result = itemRepository.findAll();
model.addAttribute("items",result);

 

 

 

items.get(위치0부터).price 이렇게 적으면 0번째 데이터의 price가 나옴

혹은 items[1] 이렇게 줄이기 가능 

근데 만약 데이터가 100개라면? 100번 이렇게 써야함 그래서 반복문을 씀 

<div class = "card">
    <div>
        <h4 th:text="${items[1].title}">바지</h4>
        <p th:text="${items.get(1).price}">7억</p>
    </div>

</div>

 

 

우리는 타임리프를 쓰니까

타임리프 반복문 

th:each="작명 :${서버에서 보낸 변수명} 하면

th가 붙은곳을 item갯수만큼 복붙해줌

 

세부적으로 꺼내주고싶을때

작명.title 이렇게 넣어주면 title을 순서대로 잘 꺼내와줌 

<div class = "card" th:each="i :${items}">
    <!--  타임리프 반복문 th:each="작명 :${서버에서 보낸 변수명} 하면 th가 붙은곳을 item갯수만큼 복붙해줌 -->
    <img src="https://placehold.co/300">
  <div>
   
      <h4 th:text="${i.title}">바지</h4>
        <p th:text="${i.price}">7억</p>
    </div>
</div>

 

 @ToString

object의 변수들을 한꺼번에 출력하는법

해당클래스에 tostring을 만들어 놓으면 됨

 

toS까지만 써도 자동완성이 나옴 

 

 

 

이런식으로 만들어쓰면 되는데 LomBok문법도 있음 

 

해당클래스 클래스명 위에 @ToString 를 붙여주면 LomBok이 알아서 만들어주고

 .toString 하면 써짐.  참고로 굳이 .toString 안붙여도 출력가능 

결과값