這篇文章主要介紹了Spring Boot怎么整合Thymeleaf的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Spring Boot怎么整合Thymeleaf文章都會有所收獲,下面我們一起來看看吧。
Spring Boot 官方推薦使用 Thymeleaf 作為其模板引擎。SpringBoot 為 Thymeleaf 提供了一系列默認配置,并且為Thymeleaf提供了視圖解析器。項目中一但導入了 Thymeleaf 的依賴,相對應的自動配置 (ThymeleafAutoConfiguration) 就會自動生效,因此 Thymeleaf 可以與 Spring Boot 完美整合 。Thymeleaf模板引擎可以和html標簽完美結合,便于后端渲染數據。Thymeleaf支持靜態效果和動態效果,在沒有動態數據的時候,會展示靜態效果模板引擎是為了使用戶界面與業務數據(內容)分離而產生的,它可以生成特定格式的文檔,用于網站的模板引擎就會生成一個標準的HTML文檔就是將模板文件和數據通過模板引擎生成一個HTML代碼**常見的模板引擎有:jsp、freemarker、velocity、thymeleafThymeleaf默認寫的位置是在templates這個目錄下面Thymeleaf官網:https://www.thymeleaf.org/
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
Thymeleaf默認的視圖路徑是:/ resources/templates,在這個目錄下面創建html并引入thymeleaf
<html lang="en" xmlns:th="http://www.thymleaf.org">
xmlns:th=“http://www.thymleaf.org”>
${域屬性名}:獲得request域中的域屬性值并顯示
${session.域屬性名}: 獲得session域中的域屬性值并顯示
< p th:text="${name}">aaa</p>如果取得到數據的話,就會渲染成動態畫面,否則就渲染成靜態畫面(只顯示學生管理系統只顯示學生管理系統這幾個字)

<span th:text="${user.name}">Tom</span>使用th:if和th:unless屬性進行條件判斷,th:unlessth:unless剛好相反,只有表達式條件不成立才會顯示內容
<h3 th:if="${age>=18}">成年</h3>
<h3 th:unless="${age>=18}">未成年</h3><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.tb-stus{
width: 900px;
margin: 0 auto;
border: black 1px solid;
border-collapse: collapse;
}
.tb-stus th,td{
padding: 10px;
text-align: center;
border:1px solid black;
}
</style>
</head>
<body>
<h3 align="center">學生管理系統</h3>
<table class="tb-stus">
<thead>
<tr>
<th>序號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>班級</th>
<th>生日</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="stu:${stuList}">
<td>1</td>
<td th:text="${stu.name}">aa</td>
<td>22</td>
<td>男</td>
<td>計科1班</td>
<td>2022-2-3</td>
<td>
<a href="#" rel="external nofollow" >刪除</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
th:href和@{}鏈接表達式
<!--http://localhost:8080/stu/10 -->
<a th:href="${'/stus/'+ stu.id}" rel="external nofollow" >編輯學生1</a>
<!--http://localhost:8080/stu?id=10 -->
<a th:href="@{/stus(id=${stu.id})}" rel="external nofollow" >編輯學生2</a>
<!--http://localhost:8080/stu?id=10&name=abc -->
<a th:href="@{/stus(id=${stu.id},name=${stu.name})}" rel="external nofollow" >編輯學生3</a>th:switch和th:case
<div th:switch="${stu.role}">
<h3 th:case="banzhang">班長</h3>
<h3 th:case="tuanzhishu">團支書</h3>
<h3 th:case="${data}">學委</h3>
<h3 th:case="*">其他</h3>
</div>thymeleaf默認給變量名+Stat的狀態
如果沒有顯示設置狀態變量,thymeleaf會默認給一個變量名+Stat的狀態
<tr th:each="stu: ${stus}">
<td th:text="${stuStat.index}"></td>
<td th:text="${ stu.name}"></td>
<td th:text="${ stu.age}"></td>
</tr>th:object可以定義對象屬性
#dates.format()可以用來格式化日期格式
*{}可以和th:object配合使用,可以取出對象中的屬性
<form th:object="${stu}">
編號:<input type="text" name="id" th:value="*{id}"><br>
姓名:<input type="text" name="name" th:value="*{name}"><br>
年齡:<input type="text" name="age" th:value="*{age}"><br>
性別:<input type="radio" name="gender" value="true" th:checked="*{gender}">男<br>
性別:<input type="radio" name="gender" value="true" th:checked="*{not gender}">女<br>
生日:<input type="text" name="birth" th:value="*{#dates.format(birth,'yyyy-MM-dd')}"><br>
<input type="submit" value="編輯">
</form>創建項目的時候,記得在模板引擎中勾選Thymeleaf

在pom.xml中把MySQL驅動的作用域刪除
然后我們這里使用druid連接池,所以需要在pom文件導入相關依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.11</version> </dependency>
然后我們需要在全局配置文件application.properties中進行相關配置
# 指定Mybatis的Mapper接口的xml映射文件的路徑 mybatis.mapper-locations=classpath:mapper/*xml # MySQL數據庫驅動 #這個驅動也可以省略,可以根據使用的MySQL自動加載相應的驅動 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 數據源名稱 spring.datasource.name=com.alibaba.druid.pool.DruidDataSource # 數據庫連接地址 spring.datasource.url=jdbc:mysql://localhost:3306/school?serverTimezone=UTC&zeroDateTimeBehavior=convertToNull # 數據庫用戶名和密碼 spring.datasource.username=root spring.datasource.password=a87684009. # 設置日志級別 logging.level.com.zyh.springboot=debug # 開啟mybatis駝峰命名規則自動轉換功能 mybatis.configuration.map-underscore-to-camel-case=true
數據庫準備 準備好數據庫中表所對應的實體類,以及三層結構


@Data
public class Stu {
private Integer id;
private String name;
private Integer age;
private Boolean gender;
private Integer cid;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birth;
}Mapper
@Mapper
public interface StuMapper {
/**
* 查詢所有學生信息
* @return
* @throws Exception
*/
@Select("select * from stu")
List<Stu> queryAllStu() throws Exception;
}Service
public interface StuService {
/**
* 查詢所有學生信息
* @return
*/
List<Stu> queryAllStu() throws Exception;
}Service的實現類
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
@Override
public List<Stu> queryAllStu() throws Exception {
return stuMapper.queryAllStu();
}
}thymeleaf
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>學生管理系統</h3>
<h3 th:text="${name}">aaaa</h3>
</body>
</html>Controller
@Controller
@RequestMapping("/stu")
public class StuController {
@Autowired
private StuService stuService;
/**
* 顯示學生管理系統的畫面
* @return
*/
@RequestMapping("/stusUi")
public String stusUi(){
return "stus";
}
}


然后我們先準備好頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.tb-stus{
width: 900px;
margin: 0 auto;
border: black 1px solid;
border-collapse: collapse;
}
.tb-stus th,td{
padding: 10px;
text-align: center;
border:1px solid black;
}
</style>
</head>
<body>
<h3 align="center">學生管理系統</h3>
<table class="tb-stus">
<thead>
<tr>
<th>序號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>班級</th>
<th>生日</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="stu,status: ${stuList}">
<td th:text="${status.index+1}">1</td>
<td th:text="${stu.name}">aa</td>
<td th:text="${stu.age}">22</td>
<!-- gender的屬性值為1表示性別為男-->
<td th:if="${stu.gender}">男</td>
<td th:unless="${stu.gender}">女</td>
<td th:text="${stu.cid}">計科1班</td>
<td th:text="${#dates.format(stu.birth,'yyyy-MM-dd')}">2022-2-3</td>
<td>
<!--http://localhost:8080/stu/delete?id=10-->
<a th:href="@{/stu/delete(id=${stu.id})}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >刪除</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
當我們點擊刪除的時候,后端要根據前端傳過來的id來從數據庫中刪除對應的數據。這里我們先按照我們之前學的時候,熟悉的方法來完成,到后面的時候,會詳細講前后端分離開發
Controller(之前的方法這里沒有粘貼出來,不然代碼太多了)
@Controller
@RequestMapping("/stu")
public class StuController {
@Autowired
private StuService stuService;
/**根據id刪除數據
* http://localhost:8080/stu/delete?id=10
* @return
*/
@RequestMapping("/delete")
public String deleteById(@RequestParam("id") Integer id){
try {
stuService.deleteByid(id);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(id);
return "redirect:/stu/stusUi";
}
}Service
public interface StuService {
/**
* 查詢所有學生信息
* @return
*/
List<Stu> queryAllStu() throws Exception;
void deleteByid(Integer id);
}Service實現類
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
@Override
public List<Stu> queryAllStu() throws Exception {
return stuMapper.queryAllStu();
}
/**
* 根據id刪除數據
* @param id
*/
@Override
public void deleteByid(Integer id) throws Exception {
stuMapper.deleteById(id);
}
}Mapper
@Mapper
public interface StuMapper {
/**
* 查詢所有學生信息
* @return
* @throws Exception
*/
@Select("select * from stu")
List<Stu> queryAllStu() throws Exception;
@Delete("delete from stu where id=#{id}")
void deleteById( Integer id);
}把編號為8的數據刪除

頁面stus.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.tb-stus{
width: 900px;
margin: 0 auto;
border: black 1px solid;
border-collapse: collapse;
}
.tb-stus th,td{
padding: 10px;
text-align: center;
border:1px solid black;
}
</style>
</head>
<body>
<h3 align="center">學生管理系統</h3>
<table class="tb-stus">
<thead>
<tr>
<th>序號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>班級</th>
<th>生日</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="stu,status: ${stuList}">
<td th:text="${stu.id}">1</td>
<td th:text="${stu.name}">aa</td>
<td th:text="${stu.age}">22</td>
<!-- gender的屬性值為1表示性別為男-->
<td th:if="${stu.gender}">男</td>
<td th:unless="${stu.gender}">女</td>
<td th:text="${stu.cid}">計科1班</td>
<td th:text="${#dates.format(stu.birth,'yyyy-MM-dd')}">2022-2-3</td>
<td>
<!-- localhost:8080/stu/delete/8-->
<!-- <a th:href="${'/stu/delete/'+stu.id}" rel="external nofollow" rel="external nofollow" >刪除</a>-->
<!--http://localhost:8080/stu/delete?id=10-->
<a th:href="@{/stu/delete(id=${stu.id})}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >刪除</a>
<a th:href="@{/stu/edit(id=${stu.id})}" rel="external nofollow" rel="external nofollow" >編輯</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>頁面 stu-edit.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>編輯畫面</title>
</head>
<body>
<h3 >編輯學生信息</h3>
<form action="" method="post" th:object="${stu}">
學號:<input type="text" name="id" th:value="*{id}" ><br><br>
姓名:<input type="text" name="name" th:value="*{name}"><br><br>
年齡:<input type="text" name="age" th:value="*{age}"><br><br>
性別:<input type="radio" name="gender" th:checked="*{gender}" >男
<input type="radio" name="gender" th:checked="*{!gender}" >女<br><br>
班級:<input type="text" name="cid" th:value="*{cid}"><br><br>
生日:<input type="text" name="birth" th:value="*{#dates.format(birth,'yyyy-MM-dd')}"><br><br>
<input type="submit" value="編輯">
</form>
</body>
</html>Controller
/**
* 根據id來修改數據
* 我們首先得先根據id把數據查詢出來,然后把數據展示出來
* 用戶再進行編輯,用戶編輯完并且提交以后,跳轉到學生管理系統畫面,展示所有數據
* @return
*/
@RequestMapping("/edit")
public String edit(@RequestParam("id") Integer id,Model model){
System.out.println("id"+id);
try {
Stu stu=stuService.queryById(id);
model.addAttribute("stu",stu);
} catch (Exception e) {
e.printStackTrace();
}
return "stu-edit";
}Service
public interface StuService {
/**
* 查詢所有學生信息
* @return
*/
List<Stu> queryAllStu() throws Exception;
/**
* 根據id來刪除學生信息
* @param id
* @throws Exception
*/
void deleteByid(Integer id) throws Exception;
/**
* 根據id來查詢對應學生信息
* @param id
* @return
* @throws Exception
*/
Stu queryById(Integer id) throws Exception;
}Service實現類
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
@Override
public List<Stu> queryAllStu() throws Exception {
return stuMapper.queryAllStu();
}
/**
* 根據id刪除數據
* @param id
*/
@Override
public void deleteByid(Integer id) throws Exception {
stuMapper.deleteById(id);
}
@Override
public Stu queryById(Integer id) throws Exception {
return stuMapper.queryById(id);
}
}Mapper
@Mapper
public interface StuMapper {
/**
* 查詢所有學生信息
* @return
* @throws Exception
*/
@Select("select * from stu")
List<Stu> queryAllStu() throws Exception;
@Delete("delete from stu where id=#{id}")
void deleteById( Integer id);
@Select("select * from stu where id=#{id}")
Stu queryById(Integer id) throws Exception;
}
比如在序號為4中,點擊編輯

登錄頁面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>用戶登錄</h3> <form action="/login" method="post"> 賬號:<input type="text" name="username"><br><br> 密碼:<input type="password" name="password"><br><br> <input type="submit" value="登錄"> </form> </body> </html>
因為需要判斷用戶是否存在,這是從數據庫進行查詢的,所以要準備對應的管理員表
# 創建管理員表 CREATE TABLE admin( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(20), `password` VARCHAR(20) ); INSERT INTO admin VALUES (DEFAULT,'aaa',111), (DEFAULT,'bbb',222), (DEFAULT,'ccc',333); # 查詢測試 SELECT * FROM admin;
準備對應的實體類
@Data
public class Admin {
private String username;
private String password;
}Controller
@Controller
@SessionAttributes(names = {"admin"})
public class AdminController {
@Autowired
private AdminService adminService;
/**
* 顯示登錄頁面
* @return
*/
@RequestMapping(value = "/loginUi")
public String loginUi(){
return "login";
}
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(String username, String password, Model model){
try {
Admin admin = adminService.login(username, password);
//用戶名存在說明登錄成功
if (admin!=null){
//存放到session域中
model.addAttribute("admin",admin);
return "redirect:/stu/stusUi";
}
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/loginUi";
}
}Service
public interface AdminService {
Admin login(String username,String password) throws Exception;
}Service對應的實現類
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
private AdminMapper adminMapper;
@Override
public Admin login(String username, String password) throws Exception {
return adminMapper.queryByUsernameAndPassword(username,password);
}
}Mapper
@Mapper
public interface AdminMapper {
@Select("select * from admin where username=#{username} and password=#{password}")
Admin queryByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.tb-stus{
width: 900px;
margin: 0 auto;
border: black 1px solid;
border-collapse: collapse;
}
.tb-stus th,td{
padding: 10px;
text-align: center;
border:1px solid black;
}
</style>
</head>
<body>
<h3 align="center">學生管理系統</h3>
<h3 th:if="${session.admin!=null}" th:text="${session.admin.username}">用戶名</h3>
<a th:unless="${session.admin!=null}" href="/loginUi" rel="external nofollow" >登錄</a>
<a th:if="${session.admin!=null}" href="/logout" rel="external nofollow" >注銷用戶</a>
<table class="tb-stus">
<thead>
<tr>
<th>序號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>班級</th>
<th>生日</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="stu,status: ${stuList}">
<td th:text="${stu.id}">1</td>
<td th:text="${stu.name}">aa</td>
<td th:text="${stu.age}">22</td>
<!-- gender的屬性值為1表示性別為男-->
<td th:if="${stu.gender}">男</td>
<td th:unless="${stu.gender}">女</td>
<td th:text="${stu.cid}">計科1班</td>
<td th:text="${#dates.format(stu.birth,'yyyy-MM-dd')}">2022-2-3</td>
<td>
<!-- localhost:8080/stu/delete/8-->
<!-- <a th:href="${'/stu/delete/'+stu.id}" rel="external nofollow" rel="external nofollow" >刪除</a>-->
<!--http://localhost:8080/stu/delete?id=10-->
<a th:href="@{/stu/delete(id=${stu.id})}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >刪除</a>
<a th:href="@{/stu/edit(id=${stu.id})}" rel="external nofollow" rel="external nofollow" >編輯</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>


注銷的話,我們把session域中的用戶對象取消,然后這個時候就得重新登錄,應該要跳轉到登錄畫面
@RequestMapping("/logout")
public String logout(HttpSession session){
session.removeAttribute("admin");
return "redirect:/loginUi";
}

關于“Spring Boot怎么整合Thymeleaf”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Spring Boot怎么整合Thymeleaf”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。