---
title: 'Thymeleaf'
disqus: hackmd
---
###### tags: `Thymeleaf`
Thymeleaf
===
[TOC]
## Thymeleaf 是什麼
Thymeleaf 是Spring Boot推薦模板,寫Thymeleaf就像是寫HTML一樣,模板頁面本身就可透過瀏覽器檢視的HTML,來進行後端與前端物件與資料的連接傳遞。
---
## Springboot專案如何導入
### Thymeleaf 設定
==pom.xml== 加入Thymeleaf dependency
```pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
## 範例程式
### ==application.yml==設定Thymeleaf config
>[Spring Thymeleaf Setting DOC](https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/ "Spring Boot Reference Guide")
** [注意] spring.thymeleaf.cache**
Spring Boot 預設使用 Thymeleaf 模版,而且預設會啟用模版快取,若開發時會修改模版,並希望能看到模版的即時變化,可以將快取關掉。
```xml=
spring.thymeleaf.cache=false /* 快取開關 */
spring.thymeleaf.encoding=UTF-8 /* 編碼型態 */
spring.thymeleaf.prefix=classpath:/templates/ /* 資料夾查詢起始位置 */
```
### 建立路徑資料夾
在templates資料夾下建立html/userSettingbackend資料夾,並在資料夾下新增users.html
![](https://i.imgur.com/Wp7laHi.png)
#### users.html內
記住要將html這段改成 ==<html lang="en" xmlns:th="https://www.thymeleaf.org">==
```htmlembedded=
<!doctype html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<title>Thymeleaf Form handling Demo</title>
<link
href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body class="container">
<h1 class="py-5">Thymeleaf Form handling Demo</h1>
<form class="col card p-3 mb-5" method="post" th:action="@{/users/}"
th:object="${userSettingInfo}">
<div class="form-group">
<label for="account">account</label> <input class="form-control"
id="account" placeholder="account" required
th:field="*{account}" type="text">
</div>
<div class="form-group">
<label for="password">password</label> <input class="form-control"
id="password" placeholder="password" required
th:field="*{password}" type="password">
</div>
<div class="form-group">
<label for="role">Role</label> <select class="form-control "
id="role" required th:field="*{role}">
<option hidden value="">Select a role</option>
<option
th:each="role : ${T(com.AICenter.Controller.backend.Definition.role).values()}"
th:text="${role}" th:value="${role}"></option>
</select>
</div>
<input class="btn btn-primary" type="submit" value="Create User">
</form>
<table class="table table-striped table-bordered">
<tr>
<th>account</th>
<th>Role</th>
<th>Created At</th>
<th>Operation</th>
</tr>
<tr th:if="${#lists.isEmpty(users)}">
<td colspan="5">No Records found. Add some...!</td>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.account}"></td>
<td th:text="${user.role}"></td>
<td th:text="${user.LastUpdateTime}"></td>
<td>
<form th:action="@{/users/deleteUser}" th:object="${deleteUserInfo}" method="post">
<input type="hidden" name="account" th:value="${user.account}">
<button type="submit">Delete</button>
</form>
</td>
</tr>
</table>
</body>
</html>
```
### userSettingEntityPK.java 和 userSettingEntity
#### ==userSettingEntityPK.java==
```java=
public class userSettingEntityPK implements Serializable {
private String account;
private String role;
/*
*
* Getter and Setter
*
* */
}
```
#### ==userSettingEntity.java==
```java=
@Entity
@IdClass(userSettingEntityPK.class)
@Table(name = "userSetting")
public class userSettingEntity implements Serializable{
@Id
@Column(name = "account")
private String account;
@Column(name = "password")
private String password;
@Id
@Column(name = "role")
private String role;
@Column(name = "LastUpdateTime",insertable = false,updatable = false,columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Date lastUpdateTime;
/*
*
* Getter and Setter
*
* */
}
```
#### ==UserSettingRepository.java==
```java=
@Repository
public interface UserSettingRepository extends JpaRepository<userSettingEntity, userSettingEntityPK>{
List<userSettingEntity> findAll();
List<userSettingEntity> findByaccount(String account);
List<userSettingEntity> findByrole(String role);
}
```
#### ==userService.java==
```java=
@Service
public class userService {
private final UserSettingRepository userSettingRepository;
public userService (UserSettingRepository userSettingRepository) {
this.userSettingRepository = userSettingRepository;
}
public List<userSettingEntity> getUserSetting() {
return userSettingRepository.findAll();
}
public userSettingEntity createUser(userSettingEntity userSettingInfo) {
return userSettingRepository.save(userSettingInfo);
}
public userSettingEntity deleteUser(List<userSettingEntity> deleteUserSettingInfo) {
userSettingRepository.deleteAll(deleteUserSettingInfo);
return null;
}
public List<userSettingEntity> findByAccount(String account) {
List<userSettingEntity> userSettingEntityList = userSettingRepository.findByaccount(account);
return userSettingEntityList;
}
}
```
#### 建立 ==userSettingController.java== controller
``` java=
@Controller
@RequestMapping("/users")
public class userSettingController {
private final userService userService;
public userSettingController (userService userService) {
this.userService = userService;
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getUsers(Model model) {
List<userSettingEntity> users = userService.getUserSetting();
model.addAttribute("users", users);
model.addAttribute("userSettingInfo", new userSettingEntity());
return "html/userSettingbackend/users";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String createUser(Model model, @ModelAttribute userSettingEntity userInfo) {
userSettingEntity user = userService.createUser(userInfo);
return "redirect:/users/";
}
@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
public String deleteUser(@ModelAttribute(value="deleteUserInfo") userSettingEntity deleteUserInfo, Model model) {
String account = deleteUserInfo.getAccount();
log.info("Account: " + account);
List<userSettingEntity> userSettingEntityList = userService.findByAccount(account);
if (!userSettingEntityList.isEmpty()) {
userService.deleteUser(userSettingEntityList);
}
List<userSettingEntity> users = userService.getUserSetting();
model.addAttribute("users", users);
model.addAttribute("userSettingInfo", new userSettingEntity());
return "redirect:/users/";
}
}
```