프로그래밍/Java

intelliJ Springboot + MyBatis + MySQL + thymeleaf 셋팅 및 연동(3)

소행성왕자 2023. 8. 18. 15:38

thymleaf 를 이용하여 html 파일을 바꿔봅시다.

TestController.java

package com.naya.shop.controller;
import com.naya.shop.dto.TestDto;
import com.naya.shop.service.TestService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class TestController {
private final TestService testService;
public TestController(TestService testService) {
this.testService = testService;
}
@RequestMapping("/")
public String test(Model model) {
model.addAttribute("name", "Hello World!");
return "main/index";
}
@RequestMapping("/user")
public String getUser(Model model) {
List<TestDto> users = testService.getUserList();
model.addAttribute("users", users);
return "users/lists";
}
}

thymleaf 사용할 디렉토리 생성

  • main 
  • users 

main/index.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${name}">Name</h1>
11
</body>
</html>

users/lists.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${users[0].title}"></div>
<div th:text="${users[0].name}"></div>
<div th:text="${users[0].reg_date}"></div>
<table class="tb_col">
<tr>
<th>idx</th>
<th>title</th>
<th>name</th>
<th>reg_date</th>
<th>update_date</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.idx}"></td>
<td th:text="${user.title}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.reg_date}"></td>
<td th:text="${user.update_date}"></td>
</tr>
</table>
</body>
</html>