您好,登錄后才能下訂單哦!
這篇文章主要介紹了Spring Boot怎么整合Thymeleaf的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Spring Boot怎么整合Thymeleaf文章都會(huì)有所收獲,下面我們一起來看看吧。
Spring Boot 官方推薦使用 Thymeleaf 作為其模板引擎。SpringBoot 為 Thymeleaf 提供了一系列默認(rèn)配置,并且為Thymeleaf提供了視圖解析器。項(xiàng)目中一但導(dǎo)入了 Thymeleaf 的依賴,相對(duì)應(yīng)的自動(dòng)配置 (ThymeleafAutoConfiguration) 就會(huì)自動(dòng)生效,因此 Thymeleaf 可以與 Spring Boot 完美整合 。Thymeleaf模板引擎可以和html標(biāo)簽完美結(jié)合,便于后端渲染數(shù)據(jù)。Thymeleaf支持靜態(tài)效果和動(dòng)態(tài)效果,在沒有動(dòng)態(tài)數(shù)據(jù)的時(shí)候,會(huì)展示靜態(tài)效果模板引擎是為了使用戶界面與業(yè)務(wù)數(shù)據(jù)(內(nèi)容)分離而產(chǎn)生的,它可以生成特定格式的文檔,用于網(wǎng)站的模板引擎就會(huì)生成一個(gè)標(biāo)準(zhǔn)的HTML文檔就是將模板文件和數(shù)據(jù)通過模板引擎生成一個(gè)HTML代碼**常見的模板引擎有:jsp、freemarker、velocity、thymeleafThymeleaf默認(rèn)寫的位置是在templates這個(gè)目錄下面Thymeleaf官網(wǎng):https://www.thymeleaf.org/
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
Thymeleaf默認(rèn)的視圖路徑是:/ resources/templates,在這個(gè)目錄下面創(chuàng)建html并引入thymeleaf
<html lang="en" xmlns:th="http://www.thymleaf.org">
xmlns:th=“http://www.thymleaf.org”>
${域?qū)傩悦鹽:獲得request域中的域?qū)傩灾挡@示
${session.域?qū)傩悦鹽: 獲得session域中的域?qū)傩灾挡@示
< p th:text="${name}">aaa</p>
如果取得到數(shù)據(jù)的話,就會(huì)渲染成動(dòng)態(tài)畫面,否則就渲染成靜態(tài)畫面(只顯示學(xué)生管理系統(tǒng)只顯示學(xué)生管理系統(tǒng)這幾個(gè)字)
<span th:text="${user.name}">Tom</span>
使用th:if和th:unless屬性進(jìn)行條件判斷,th:unlessth:unless剛好相反,只有表達(dá)式條件不成立才會(huì)顯示內(nèi)容
<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">學(xué)生管理系統(tǒng)</h3> <table class="tb-stus"> <thead> <tr> <th>序號(hào)</th> <th>姓名</th> <th>年齡</th> <th>性別</th> <th>班級(jí)</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>計(jì)科1班</td> <td>2022-2-3</td> <td> <a href="#" rel="external nofollow" >刪除</a> </td> </tr> </tbody> </table> </body> </html>
th:href和@{}鏈接表達(dá)式
<!--http://localhost:8080/stu/10 --> <a th:href="${'/stus/'+ stu.id}" rel="external nofollow" >編輯學(xué)生1</a> <!--http://localhost:8080/stu?id=10 --> <a th:href="@{/stus(id=${stu.id})}" rel="external nofollow" >編輯學(xué)生2</a> <!--http://localhost:8080/stu?id=10&name=abc --> <a th:href="@{/stus(id=${stu.id},name=${stu.name})}" rel="external nofollow" >編輯學(xué)生3</a>
th:switch和th:case
<div th:switch="${stu.role}"> <h3 th:case="banzhang">班長</h3> <h3 th:case="tuanzhishu">團(tuán)支書</h3> <h3 th:case="${data}">學(xué)委</h3> <h3 th:case="*">其他</h3> </div>
thymeleaf默認(rèn)給變量名+Stat的狀態(tài)
如果沒有顯示設(shè)置狀態(tài)變量,thymeleaf會(huì)默認(rèn)給一個(gè)變量名+Stat的狀態(tài)
<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可以定義對(duì)象屬性
#dates.format()可以用來格式化日期格式
*{}可以和th:object配合使用,可以取出對(duì)象中的屬性
<form th:object="${stu}"> 編號(hào):<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>
創(chuàng)建項(xiàng)目的時(shí)候,記得在模板引擎中勾選Thymeleaf
在pom.xml中把MySQL驅(qū)動(dòng)的作用域刪除
然后我們這里使用druid連接池,所以需要在pom文件導(dǎo)入相關(guān)依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.11</version> </dependency>
然后我們需要在全局配置文件application.properties中進(jìn)行相關(guān)配置
# 指定Mybatis的Mapper接口的xml映射文件的路徑 mybatis.mapper-locations=classpath:mapper/*xml # MySQL數(shù)據(jù)庫驅(qū)動(dòng) #這個(gè)驅(qū)動(dòng)也可以省略,可以根據(jù)使用的MySQL自動(dòng)加載相應(yīng)的驅(qū)動(dòng) spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 數(shù)據(jù)源名稱 spring.datasource.name=com.alibaba.druid.pool.DruidDataSource # 數(shù)據(jù)庫連接地址 spring.datasource.url=jdbc:mysql://localhost:3306/school?serverTimezone=UTC&zeroDateTimeBehavior=convertToNull # 數(shù)據(jù)庫用戶名和密碼 spring.datasource.username=root spring.datasource.password=a87684009. # 設(shè)置日志級(jí)別 logging.level.com.zyh.springboot=debug # 開啟mybatis駝峰命名規(guī)則自動(dòng)轉(zhuǎn)換功能 mybatis.configuration.map-underscore-to-camel-case=true
數(shù)據(jù)庫準(zhǔn)備 準(zhǔn)備好數(shù)據(jù)庫中表所對(duì)應(yīng)的實(shí)體類,以及三層結(jié)構(gòu)
@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 { /** * 查詢所有學(xué)生信息 * @return * @throws Exception */ @Select("select * from stu") List<Stu> queryAllStu() throws Exception; }
Service
public interface StuService { /** * 查詢所有學(xué)生信息 * @return */ List<Stu> queryAllStu() throws Exception; }
Service的實(shí)現(xiàn)類
@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>學(xué)生管理系統(tǒng)</h3> <h3 th:text="${name}">aaaa</h3> </body> </html>
Controller
@Controller @RequestMapping("/stu") public class StuController { @Autowired private StuService stuService; /** * 顯示學(xué)生管理系統(tǒng)的畫面 * @return */ @RequestMapping("/stusUi") public String stusUi(){ return "stus"; } }
然后我們先準(zhǔn)備好頁面
<!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">學(xué)生管理系統(tǒng)</h3> <table class="tb-stus"> <thead> <tr> <th>序號(hào)</th> <th>姓名</th> <th>年齡</th> <th>性別</th> <th>班級(jí)</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}">計(jì)科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>
當(dāng)我們點(diǎn)擊刪除的時(shí)候,后端要根據(jù)前端傳過來的id來從數(shù)據(jù)庫中刪除對(duì)應(yīng)的數(shù)據(jù)。這里我們先按照我們之前學(xué)的時(shí)候,熟悉的方法來完成,到后面的時(shí)候,會(huì)詳細(xì)講前后端分離開發(fā)
Controller(之前的方法這里沒有粘貼出來,不然代碼太多了)
@Controller @RequestMapping("/stu") public class StuController { @Autowired private StuService stuService; /**根據(jù)id刪除數(shù)據(jù) * 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 { /** * 查詢所有學(xué)生信息 * @return */ List<Stu> queryAllStu() throws Exception; void deleteByid(Integer id); }
Service實(shí)現(xiàn)類
@Service public class StuServiceImpl implements StuService { @Autowired private StuMapper stuMapper; @Override public List<Stu> queryAllStu() throws Exception { return stuMapper.queryAllStu(); } /** * 根據(jù)id刪除數(shù)據(jù) * @param id */ @Override public void deleteByid(Integer id) throws Exception { stuMapper.deleteById(id); } }
Mapper
@Mapper public interface StuMapper { /** * 查詢所有學(xué)生信息 * @return * @throws Exception */ @Select("select * from stu") List<Stu> queryAllStu() throws Exception; @Delete("delete from stu where id=#{id}") void deleteById( Integer id); }
把編號(hào)為8的數(shù)據(jù)刪除
頁面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">學(xué)生管理系統(tǒng)</h3> <table class="tb-stus"> <thead> <tr> <th>序號(hào)</th> <th>姓名</th> <th>年齡</th> <th>性別</th> <th>班級(jí)</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}">計(jì)科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 >編輯學(xué)生信息</h3> <form action="" method="post" th:object="${stu}"> 學(xué)號(hào):<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> 班級(jí):<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
/** * 根據(jù)id來修改數(shù)據(jù) * 我們首先得先根據(jù)id把數(shù)據(jù)查詢出來,然后把數(shù)據(jù)展示出來 * 用戶再進(jìn)行編輯,用戶編輯完并且提交以后,跳轉(zhuǎn)到學(xué)生管理系統(tǒng)畫面,展示所有數(shù)據(jù) * @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 { /** * 查詢所有學(xué)生信息 * @return */ List<Stu> queryAllStu() throws Exception; /** * 根據(jù)id來刪除學(xué)生信息 * @param id * @throws Exception */ void deleteByid(Integer id) throws Exception; /** * 根據(jù)id來查詢對(duì)應(yīng)學(xué)生信息 * @param id * @return * @throws Exception */ Stu queryById(Integer id) throws Exception; }
Service實(shí)現(xiàn)類
@Service public class StuServiceImpl implements StuService { @Autowired private StuMapper stuMapper; @Override public List<Stu> queryAllStu() throws Exception { return stuMapper.queryAllStu(); } /** * 根據(jù)id刪除數(shù)據(jù) * @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 { /** * 查詢所有學(xué)生信息 * @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; }
比如在序號(hào)為4中,點(diǎn)擊編輯
登錄頁面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>用戶登錄</h3> <form action="/login" method="post"> 賬號(hào):<input type="text" name="username"><br><br> 密碼:<input type="password" name="password"><br><br> <input type="submit" value="登錄"> </form> </body> </html>
因?yàn)樾枰袛嘤脩羰欠翊嬖?,這是從數(shù)據(jù)庫進(jìn)行查詢的,所以要準(zhǔn)備對(duì)應(yīng)的管理員表
# 創(chuàng)建管理員表 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;
準(zhǔn)備對(duì)應(yīng)的實(shí)體類
@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對(duì)應(yīng)的實(shí)現(xiàn)類
@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">學(xué)生管理系統(tǒng)</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>序號(hào)</th> <th>姓名</th> <th>年齡</th> <th>性別</th> <th>班級(jí)</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}">計(jì)科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域中的用戶對(duì)象取消,然后這個(gè)時(shí)候就得重新登錄,應(yīng)該要跳轉(zhuǎn)到登錄畫面
@RequestMapping("/logout") public String logout(HttpSession session){ session.removeAttribute("admin"); return "redirect:/loginUi"; }
關(guān)于“Spring Boot怎么整合Thymeleaf”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Spring Boot怎么整合Thymeleaf”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。