Thymeleaf로 객체 값 얻어오기

2024. 6. 14. 18:46JSP+Spring Boot

* StudentDTO.java 파일 생성

package com.example.demo.DTO;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

/*
	Spring은 getter가 필수로 있어야함
	-> ${StudentDTO.getName()} == ${StudentDTO.name}
	
	-> getter 대신 필드명 호출하는 형식(${StudentDTO.name})
	-> getter를 자동으로 호출하기 때문
*/


@Getter
@Setter	//getter, setter 메서드 자동 추가
@NoArgsConstructor // 기본 생성자 자동 추가
@AllArgsConstructor // 필수 생성자 자동 추가
@ToString // toString 메서드 자동 오버라이딩 추가
public class StudentDTO {
	
	private String studentNo;
	private String name;
	private int age;
}

 

방법 1 -> Model 사용해서 html로 값 전달

@GetMapping("ex1")
public String ex1(HttpServletRequest req, Model model) {

    //DTO 객체 Model을 이용해서 html로 전달
    StudentDTO std = new StudentDTO();
    std.setStudentNo("12345");
    std.setName("홍길동");
    std.setAge(30);
    model.addAttribute("std",std);
}

 

<h4>방법1</h4>
<ul>
    <li th:text="${std}">std 객체</li> 
    <!-- StudentDTO(studentNo=12345, name=홍길동, age=30) -->
    <li th:text="${std.studentNo}">학번</li> <!-- 12345 -->
    <li th:text="${std.name}">이름</li> <!-- 홍길동 -->
    <li th:text="${std.age}">나이</li> <!-- 30 -->  	
</ul>

방법1

 

**

<li th:text="${별칭}">객체</li>
model.addAttribute("별칭",임의의 별칭);

* 두 별칭은 같아야함.

나중에 이름이 다르면 문제가 생겼을 때 찾기 어려우므로 
'별칭'과 '임의의 별칭'을 동일하게 설정해주는게 좋음

 

------------------------------------------------------------------------------------------------

 

방법 2 -> th:Object 사용

 

th:object 속성 + *{필드명}
  - th:object 속성 : 해당 태그 내에서 지정된 객체의 필드를 쉽게 접근하게 해주는 속성

  - *{ } : th:object로 지정된 객체의 필드로 접근할 때 사용하는 방법

 

<h4>방법2</h4>
<ul th:object="${std}">
    <li th:text="*{studentNo}">학번</li>
    <li th:text="*{name}">이름</li>
    <li th:text="*{age}">나이</li>
</ul>

방법2

 

 

방법3 -> List, 배열과 table 태그를 활용해 모두 출력하기

 

<h4>방법3</h4>
<h5>DTO가 담긴 리스트 출력하기</h5>
<table border="1">
    <thead>
        <tr>
            <th>학번</th>
            <th>이름</th>
            <th>나이</th>
        </tr>    	
    </thead>
    <tbody>
        <!-- th:each가 설정된 태그 전체(tr) 반복됨 -->
         <tr th:each="std : ${stdList}" th:object="${std}">
            <td th:text="*{studentNo}"></td>
            <td th:text="*{name}"></td>
            <td th:text="*{age}"></td>
         </tr>
    </tbody>
</table>

 

List<StudentDTO> stdList = new ArrayList<>();

stdList.add(new StudentDTO("1111", "김일번", 10));		
stdList.add(new StudentDTO("2222", "김이번", 20));
stdList.add(new StudentDTO("3333", "김삼번", 30));		
model.addAttribute("stdList",stdList);

 

방법3

 

 

**th로 시작하는 타임리프를 쓸 때는 "와 { 사이에 @ * $ 중 하나를 무조건 작성 

@ : 주소값을 가져올때 작성, 만약 변경되는 주소값을 넣지 않으면 th를 쓰지 않아도 되지만
검색을 하거나 특정 상품을 가져오는 등 주소값에 변경이 필요할 때는 @(th:action)을 써줘야함
-> 검색이나 상품 상세보기를 할 때 주로 사용

$ : db나 controller에서 특정한 변수명을 가져와서 변수명에 담긴 정보를 이용할 때 사용

* : $로 가져온 변수명을 앞에 붙여서 사용하겠다는 의미.

'JSP+Spring Boot' 카테고리의 다른 글

Thymeleaf (if, unless)  (0) 2024.06.14
Thymeleaf(parameter, utext)  (0) 2024.06.14
Thymeleaf(block, text, each)  (0) 2024.06.14
Thymeleaf  (0) 2024.06.14
@ModelAttibute  (0) 2024.06.12