天天看點

Spring Boot整合Thymeleaf

✨Spring Boot整合Thymeleaf

  • ​​Thymeleaf​​
  • ​​基本介紹​​
  • ​​Thymeleaf預設的視圖路徑是:/ resources/templates,在這個目錄下面建立html并引入thymeleaf​​
  • ​​基本文法​​
  • ​​th:text文本替換​​
  • ​​th:if和th:unless文本替換​​
  • ​​th:each foreach循環​​
  • ​​th:href和@{}連結表達式​​
  • ​​th:switch和th:case​​
  • ​​thymeleaf預設給變量名+Stat的狀态​​
  • ​​th:id、th:value、th:checked等(和form表單相關)​​
  • ​​#dates.format()可以用來格式化日期格式​​
  • ​​整合Thymeleaf​​
  • ​​基本配置​​
  • ​​資料庫準備​​
  • ​​準備好資料庫中表所對應的實體類,以及三層結構​​
  • ​​三層架構​​
  • ​​删除操作​​
  • ​​編輯操作​​
  • ​​使用者登入​​
  • ​​使用者登出​​

Thymeleaf

基本介紹

  • Spring Boot 官方推薦使用 Thymeleaf 作為其模闆引擎。SpringBoot 為 Thymeleaf 提供了一系列預設配置,并且為Thymeleaf提供了視圖解析器。
  • 項目中一但導入了 Thymeleaf 的依賴,相對應的自動配置 (ThymeleafAutoConfiguration) 就會自動生效,是以 Thymeleaf 可以與 Spring Boot 完美整合 。
  • Thymeleaf模闆引擎可以和html标簽完美結合,便于後端渲染資料。
  • Thymeleaf支援靜态效果和動态效果,在沒有動态資料的時候,會展示靜态效果
  • 模闆引擎是為了使使用者界面與業務資料(内容)分離而産生的,它可以生成特定格式的文檔,用于網站的模闆引擎就會生成一個标準的HTML文檔就是将模闆檔案和資料通過模闆引擎生成一個HTML代碼**
  • 常見的模闆引擎有:jsp、​​freemarker​​、velocity、thymeleaf
  • Thymeleaf預設寫的位置是在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>      

如果取得到資料的話,就會渲染成動态畫面,否則就渲染成靜态畫面(隻顯示學生管理系統隻顯示學生管理系統這幾個字)

Spring Boot整合Thymeleaf

th:text文本替換

<span th:text="${user.name}">Tom</span>      

th:if和th:unless文本替換

使用th:if和th:unless屬性進行條件判斷,th:unlessth:unless剛好相反,隻有表達式條件不成立才會顯示内容
<h2 th:if="${age>=18}">成年</h2>
<h2 th:unless="${age>=18}">未成年</h2>      

th:each foreach循環

<!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>
    <h2 align="center">學生管理系統</h2>
    <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="#">删除</a>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>      
Spring Boot整合Thymeleaf

​​IDEA使用Thymeleaf輸入 th: 沒有智能提示的全新解決辦法​​

th:href和@{}連結表達式

<!--http://localhost:8080/stu/10 -->
<a th:href="${'/stus/'+ stu.id}">編輯學生1</a>

<!--http://localhost:8080/stu?id=10 -->
<a th:href="@{/stus(id=${stu.id})}">編輯學生2</a>

<!--http://localhost:8080/stu?id=10&name=abc -->
<a th:href="@{/stus(id=${stu.id},name=${stu.name})}">編輯學生3</a>      

th:switch和th:case

<div th:switch="${stu.role}">
  <h2 th:case="banzhang">班長</h2>
  <h2 th:case="tuanzhishu">團支書</h2>
  <h2 th:case="${data}">學委</h2>
  <h2 th:case="*">其他</h2>
  
</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:id、th:value、th:checked等(和form表單相關)

th:object可以定義對象屬性

*{}可以和th:object配合使用,可以取出對象中的屬性

#dates.format()可以用來格式化日期格式

<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

基本配置

建立項目的時候,記得在模闆引擎中勾選Thymeleaf
Spring Boot整合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      

資料庫準備

準備好資料庫中表所對應的實體類,以及三層結構

Spring Boot整合Thymeleaf
![image.png](https://img-blog.csdnimg.cn/img_convert/adea584ea15da55fb398cebbb282e794.png#clientId=u282232e8-2213-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=705&id=ude1680f0&margin=[object Object]&name=image.png&originHeight=793&originWidth=537&originalType=binary&ratio=1&rotatinotallow=0&showTitle=false&size=30764&status=done&style=none&taskId=u0fd3adf8-2c2c-4370-ab0b-4c873e356a3&title=&width=477.3333333333333)
@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>
    <h2>學生管理系統</h2>
    <h2 th:text="${name}">aaaa</h2>
  </body>
</html>      

Controller

@Controller
@RequestMapping("/stu")
public class StuController {
    @Autowired
    private StuService stuService;
    /**
    * 顯示學生管理系統的畫面
    * @return
    */
    @RequestMapping("/stusUi")
    public String stusUi(){
        return "stus";
    }
}      
Spring Boot整合Thymeleaf
Spring Boot整合Thymeleaf
Spring Boot整合Thymeleaf

然後我們先準備好頁面

<!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>
<h2 align="center">學生管理系統</h2>
<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})}">删除</a>
        </td>
    </tr>
    </tbody>
</table>
</body>
</html>      
Spring Boot整合Thymeleaf

當我們點選删除的時候,後端要根據前端傳過來的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的資料删除

Spring Boot整合Thymeleaf

編輯操作

頁面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>
<h2 align="center">學生管理系統</h2>
<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}">删除</a>-->
            <!--http://localhost:8080/stu/delete?id=10-->
            <a th:href="@{/stu/delete(id=${stu.id})}">删除</a>
            <a th:href="@{/stu/edit(id=${stu.id})}">編輯</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>
    <h2 >編輯學生資訊</h2>
    <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;
}      
Spring Boot整合Thymeleaf

比如在序号為4中,點選編輯

Spring Boot整合Thymeleaf

使用者登入

登入頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>使用者登入</h2>
    <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);
}      
Spring Boot整合Thymeleaf
Spring Boot整合Thymeleaf
<!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>
    <h2 align="center">學生管理系統</h2>
    <h2 th:if="${session.admin!=null}" th:text="${session.admin.username}">使用者名</h2>
    <a th:unless="${session.admin!=null}" href="/loginUi">登入</a>
    <a th:if="${session.admin!=null}" href="/logout">登出使用者</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}">删除</a>-->
            <!--http://localhost:8080/stu/delete?id=10-->
            <a th:href="@{/stu/delete(id=${stu.id})}">删除</a>
            <a th:href="@{/stu/edit(id=${stu.id})}">編輯</a>
        </td>
    </tr>
    </tbody>
</table>

</body>
</html>      
Spring Boot整合Thymeleaf
Spring Boot整合Thymeleaf
Spring Boot整合Thymeleaf

使用者登出

登出的話,我們把session域中的使用者對象取消,然後這個時候就得重新登入,應該要跳轉到登入畫面

@RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("admin");
        return "redirect:/loginUi";
    }      
Spring Boot整合Thymeleaf