[SpringBoot——Web開發(使用Thymeleaf模板引擎)]

  • 2019 年 10 月 6 日
  • 筆記

【文字只能描述片段資訊,具體細節參考程式碼】

https://github.com/HCJ-shadow/SpringBootPlus

引入POM依賴

 <properties>          <java.version>1.8</java.version>          <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>          <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>  </properties>
  <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-thymeleaf</artifactId>          </dependency>

記坑thymeleaf無法跳轉:https://blog.csdn.net/qq_40754146/article/details/95411413

將html頁面放於classpath:template/下,thymeleaf就可自動渲染。

啟動:

註:如果static下有index.html文件,系統會優先訪問static下的index.html。

設置Thymeleaf頁面跳轉

新建一個controller

在templates下新建一個thymeleaf.html

訪問:http://localhost:8080/thymeleaf

Thymeleaf CRUD測試

基礎環境準備:

– 引入資料庫相關pom依賴

  <dependency>              <groupId>org.mybatis.spring.boot</groupId>              <artifactId>mybatis-spring-boot-starter</artifactId>              <version>2.1.0</version>          </dependency>            <dependency>              <groupId>mysql</groupId>              <artifactId>mysql-connector-java</artifactId>              <scope>runtime</scope>          </dependency>

– 引入Bootstrap依賴

 <!--引入bootstrap-->          <dependency>              <groupId>org.webjars</groupId>              <artifactId>bootstrap</artifactId>              <version>4.0.0</version>          </dependency>        頁面引用:     <link  th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">

– 引入pageshelper插件

 <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->          <dependency>              <groupId>com.github.pagehelper</groupId>              <artifactId>pagehelper-spring-boot-starter</artifactId>              <version>1.2.5</version>          </dependency>

配置yaml

pagehelper:    helperDialect: mysql    reasonable: true    supportMethodsArguments: true    pageSizeZero: false #pageSize=0

1.創建資料庫表

2.創建bean適配數據表

package zkkrun.top.web.bean;    import java.io.Serializable;    public class UserInfo implements Serializable {        private Integer id;      private String username;      private String password;      private Integer age;      private String email;        public UserInfo() {      }        public UserInfo(Integer id, String username, String password, Integer age, String email) {          this.id = id;          this.username = username;          this.password = password;          this.age = age;          this.email = email;      }        public Integer getId() {          return id;      }        public void setId(Integer id) {          this.id = id;      }        public String getUsername() {          return username;      }        public void setUsername(String username) {          this.username = username;      }        public String getPassword() {          return password;      }        public void setPassword(String password) {          this.password = password;      }        public Integer getAge() {          return age;      }        public void setAge(Integer age) {          this.age = age;      }        public String getEmail() {          return email;      }        public void setEmail(String email) {          this.email = email;      }        @Override      public String toString() {          return "UserInfo{" +                  "id=" + id +                  ", username='" + username + ''' +                  ", password='" + password + ''' +                  ", age=" + age +                  ", email='" + email + ''' +                  '}';      }  }

3.yaml配置數據源

spring:    datasource:      #   數據源基本配置      username: noneplus1      password: Noneplus564925080!1      driver-class-name: com.mysql.jdbc.Driver      url: jdbc:mysql://47.113.6.247:3306/user?serverTimezone=UTC

4.創建Mapper介面,使用註解版Mybatis

package zkrun.top.web.mapper;    import org.apache.ibatis.annotations.Delete;  import org.apache.ibatis.annotations.Insert;  import org.apache.ibatis.annotations.Select;  import org.apache.ibatis.annotations.Update;  import org.springframework.stereotype.Repository;  import zkrun.top.web.bean.UserInfo;    @Repository  public interface UserInfoMapper {        @Select("SELECT * FROM user_info WHERE id = #{id}")      public UserInfo getUserById(Integer id);        @Update("UPDATE user_info SET username=#{username},password=#{password},age=#{age},email=#{email} WHERE id=#{id}")      public void updateUser(UserInfo userInfo);        @Delete("DELETE FROM user_info WHERE id=#{id}")      public void deleteUserById(Integer id);        @Insert("INSERT INTO user_info(username,password,age,email) VALUES(#{username},#{password},#{age},#{email})")      public void insertUser(UserInfo userInfo);    }

使用MapperScan掃描mapper介面所在包

@MapperScan("zkrun.top.web.mapper")

5.測試資料庫

批量插入數據

package zkrun.top.web;    import org.junit.Test;  import org.junit.runner.RunWith;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.boot.test.context.SpringBootTest;  import org.springframework.test.context.junit4.SpringRunner;  import zkrun.top.web.bean.UserInfo;  import zkrun.top.web.mapper.UserInfoMapper;    import java.util.UUID;    @RunWith(SpringRunner.class)  @SpringBootTest  public class WebApplicationTests {        @Autowired      UserInfoMapper userInfoMapper;      @Test      public void contextLoads() {            UserInfo userInfo = userInfoMapper.getUserById(1);          System.out.println(userInfo);        }        @Test      public void insertDatas() {            for(int i =0;i<1000;i++)          {              UserInfo userInfo = new UserInfo(i+2,UUID.randomUUID().toString().substring(0,8),"123456789",(Integer) (i+50)/3,"@sina.com");              userInfoMapper.insertUser(userInfo);          }          System.out.println("插入成功!");        }    }

顯示資訊列表

取消thymeleaf快取

spring:    thymeleaf:      cache: false

ctrl+shift+F9刷新

1.UserInfoMapper增加SQL查詢,獲取所有資訊

@Select("SELECT * FROM user_info")      public List<UserInfo> getUsers();

2.創建CRUDController,使用PageHelper插件分頁

@Controller  public class CRUDController {        @Autowired      UserInfoMapper userInfoMapper;        @RequestMapping("/crud")      public String crud(@RequestParam(defaultValue = "1") int pageNum,                         @RequestParam(defaultValue = "10") int pageSize,                         Model model)      {          //默認查詢所有資訊          PageHelper.startPage(pageNum,pageSize);          PageInfo<UserInfo> pageInfo = new PageInfo<UserInfo>(userInfoMapper.getUsers());          model.addAttribute("pageInfo",pageInfo);          return "crud";      }      }
  • pageNum,pageSize表示起始頁和每頁顯示的數據量,通過@RequestParam參數將默認值設為1和10,方便設置下一頁和上一頁跳轉。
  • PageHelper.startPage(pageNum,pageSize);設置起始頁和每頁顯示的數據量
  • PageInfo pageInfo = new PageInfo(userInfoMapper.getUsers());將查詢到的數據賦給pageInfo對象
  • model.addAttribute("pageInfo",pageInfo);將pageInfo傳輸進頁面

3.Thymeleaf通過表達式適配數據

<table class="table">      <tr>          <th>id</th>          <th>username</th>          <th>password</th>          <th>age</th>          <th>email</th>      </tr>      <tr th:each="user:${pageInfo.list}">          <td th:text="${user.id}"></td>          <td th:text="${user.username}"></td>          <td th:text="${user.password}"></td>          <td th:text="${user.age}"></td>          <td th:text="${user.email}"></td>      </tr>  </table>    <ul class="pagination" style="margin-left: 50%">      <li class="page-item"><a class="page-link"><span th:text="第+${pageInfo.pageNum}+頁"></span></a></li>      <li class="page-item"><a class="page-link" th:href="@{/crud}">首頁</a></li>      <li class="page-item"><a class="page-link" th:href="@{/crud(pageNum=${pageInfo.pages})}">尾頁</a></li>      <li class="page-item"><a class="page-link" th:href="@{/crud(pageNum=${pageInfo.prePage})}">Last</a></li>      <li class="page-item"><a class="page-link" th:href="@{/crud(pageNum=${pageInfo.getNextPage()})}">Next</a></li>  </ul>

訪問http://localhost:8080/crud

刪除資訊

Controller

//刪除      @RequestMapping("/delete")      public String delete(int id) {          userInfoMapper.deleteUserById(id);          return "redirect:/user";      }

UserInfoMapper

 @Delete("DELETE FROM user_info WHERE id=#{id}")      public void deleteUserById(Integer id);

在頁面添加一個按鈕

   <button type="button" class="btn btn-danger"><a style="color: aliceblue" th:href="@{/delete(id=${user.id})}">刪除</a></button>

修改和添加資訊

先跳轉到修改或者添加頁面,再進行表單提交

修改

//點擊修改按鈕,跳轉到修改頁面,回顯資訊      @RequestMapping("/modify")      public String modify(int id ,Model model) {          model.addAttribute("OneInfo",userInfoMapper.getUserById(id));          return "modify";      }        //提交修改資訊      @RequestMapping("/modifyCommit")      public String modify(UserInfo userInfo) {          System.out.println(userInfo);          userInfoMapper.updateUser(userInfo);          System.out.println("修改提交.");          return "redirect:/user";      }

主頁添加一個修改按鈕

 <button type="button" class="btn btn-primary"><a style="color: aliceblue" th:href="@{/modify(id=${user.id})}">修改</a></button>

響應上述第一個請求,跳轉到modify頁面

modify頁面

<!DOCTYPE html>  <html lang="en" xmlns:th="http://www.thymeleaf.org">  <head>      <meta charset="UTF-8">      <title>modify</title>      <link  th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">  </head>  <body>  <div style="width: 50%;margin-left: 25%;margin-top: 5%">      <h1>修改</h1>      <form class="form-horizontal" th:action="@{/modifyCommit}">          <input name="id" class="form-control"  th:value="${OneInfo.getId()}" style="display: none">          <div class="form-group">              <label  class="col-sm-2 control-label">Username</label>              <div class="col-sm-10">                  <input name="username" class="form-control" id="Username" placeholder="Username" th:value="${OneInfo.getUsername()}">              </div>          </div>          <div class="form-group">              <label  class="col-sm-2 control-label">Password</label>              <div class="col-sm-10">                  <input name="password" class="form-control" id="inputPassword3" placeholder="Password" th:value="${OneInfo.getPassword()}">              </div>          </div>          <div class="form-group">              <label  class="col-sm-2 control-label">age</label>              <div class="col-sm-10">                  <input name="age" class="form-control" id="age" placeholder="Age" th:value="${OneInfo.getAge()}">              </div>          </div>          <div class="form-group">              <label  class="col-sm-2 control-label">Email</label>              <div class="col-sm-10">                  <input name="email" class="form-control" id="inputEmail3" placeholder="Email" th:value="${OneInfo.getEmail()}">              </div>          </div>          <div class="form-group">              <div class="col-sm-offset-2 col-sm-10">                  <button type="submit" class="btn btn-primary">提交</button>              </div>          </div>      </form>  </div>  </body>  </html>

其中modify表的action響應修改表的提交操作

添加

同理,跳轉到添加頁面,再進行表單提交

controller

    //添加:1.跳轉到添加頁面      @RequestMapping("/add1")      public String add1() {          return "add";      }        //添加 : 2.提交資訊      @RequestMapping("/add2")      public String add2(UserInfo userInfo) {          System.out.println(userInfo);          userInfoMapper.insertUser(userInfo);          return "redirect:/user";      }

添加一個按鈕

<button style="margin-left: 75%" type="button" class="btn btn-primary"><a style="color: aliceblue" th:href="@{/add1}">新增</a></button>

添加頁面(對比修改頁面不需要回顯)

<!DOCTYPE html>  <html lang="en" xmlns:th="http://www.thymeleaf.org">  <head>      <meta charset="UTF-8">      <title>add</title>      <link  th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">  </head>  <body>  <div style="width: 50%;margin-left: 25%;margin-top: 5%">  <h1>添加</h1>  <form class="form-horizontal" th:action="@{/add2}">      <div class="form-group">          <label  class="col-sm-2 control-label">Username</label>          <div class="col-sm-10">              <input name="username" class="form-control" id="Username" placeholder="Username">          </div>      </div>      <div class="form-group">          <label  class="col-sm-2 control-label">Password</label>          <div class="col-sm-10">              <input name="password" class="form-control" id="inputPassword3" placeholder="Password">          </div>      </div>      <div class="form-group">          <label  class="col-sm-2 control-label">age</label>          <div class="col-sm-10">              <input name="age" class="form-control" id="age" placeholder="Age">          </div>      </div>      <div class="form-group">          <label  class="col-sm-2 control-label">Email</label>          <div class="col-sm-10">              <input name="email" class="form-control" id="inputEmail3" placeholder="Email">          </div>      </div>      <div class="form-group">          <div class="col-sm-offset-2 col-sm-10">              <button type="submit" class="btn btn-primary">提交</button>          </div>      </div>  </form>  </div>  </body>  </html>

測試

插入500條測試數據

 @Test      public void insertDatas() {            System.out.println("開始插入...");            for(int i =1;i<500;i++)          {              UserInfo userInfo = new UserInfo(i,UUID.randomUUID().toString().substring(0,8),"123456789",(Integer) (i+50)/3,"@sina.com");              userInfoMapper.insertUser(userInfo);          }          System.out.println("插入成功!");        }

顯示資訊列表

修改

添加