SpringBoot集成thymeleaf增刪改查示例

有小夥伴找我要個 thymeleaf 的 demo,說自己集成的總是報錯,所以就有了這篇...

關於什麼是 thymeleaf 我就不贅述了,相信搜到這篇的大部分是奔着如何集成來的。

本文源碼先附上:https://gitee.com/niceyoo/springboot-thymeleaf-demo

懶得看下文的可直接跳轉至源碼。下面把一些主要的配置粘一下,不做額外贅述,大部分可以在上方源碼中獲取,尤其是前端部分。

1、本文環境

  • IDEA,2021.2
  • JDK,8
  • SpringBoot,2.4.4
  • MybatisPlus,3.1.1
  • Thymeleaf,2.4.4
  • layui,2.5.6

2、依賴環境(pom.xml)

直接用的 spring-boot-starter-parent,不瞭解的可以看下這篇文章: https://www.cnblogs.com/niceyoo/p/10960207.html

主要依賴有:druid連接池、mybatisplus、mysql驅動、thymeleaf依賴。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.4</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!--web-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--新增durid監控-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.23</version>
    </dependency>
    <!--Mybatis-plus-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus</artifactId>
        <version>3.1.1</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.1.1</version>
    </dependency>
    <!-- mysql -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>
    <!--thymeleaf-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3、配置文件(application.yaml)

主要定義了 數據庫、thymeleaf、mybatisplus配置。

server:
  port: 8089

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/thymeleaf-db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
  thymeleaf:
    #模板的模式,支持 HTML, XML TEXT JAVASCRIPT
    mode: HTML5
    #編碼 可不用配置
    encoding: UTF-8
    #內容類別,可不用配置
    content-type: text/html
    #開發配置爲false,避免修改模板還要重啓服務器
    cache: false
    #配置模板路徑,默認是templates,可以不用配置
    prefix: classpath:/templates
    suffix: .html

mybatis-plus:
  typeAliasesPackage: com.thymeleaf.demo.com.thymeleaf.demo.entity
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true
    lazyLoadingEnabled: true
    multipleResultSetsEnabled: true
    #這個配置會將執行的sql打印出來,在開發或測試的時候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

用到的SQL:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(32) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `nick_name` varchar(64) DEFAULT NULL,
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

4、MyBatisPlus配置類(可忽略)

mybatisplus配置類,設置掃描包、加入分頁插件。在 mybatisplus 3.4版本之後 PaginationInterceptor 棄用了,改用 MybatisPlusInterceptor,不瞭解的可自行搜索。至於爲什麼要使用自定義分頁插件可參考方法註釋解釋。

@EnableTransactionManagement
@Configuration
@MapperScan("com.thymeleaf.demo.dao")
public class MyBatisPlus {

    /**
     * myabtis 實現的分頁爲什麼還要分頁插件?
     * <p>
     * 1.mybatis實現得分頁時邏輯分頁或者叫做內存不是物理分頁
     * 2.他是把符合條件的數據全部查詢出來放到內存中,然後返回你需要的那部分
     * 3.表中數據不多時,可以使用,速度慢一些;當數據量大時,建議使用物理分頁
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
      return new PaginationInterceptor();
    }

}

5、控制層(UserController)

如下寫了個增刪改查的實例,沒有按照代碼規範來,大致看一下即可。

其中返回 ModelAndView 的方法是用來映射對應的前端頁面的,返回 R 的方法是接口返回形式。其中 R 是 mybatisplus 中提供的一個返回給前端信息的工具類,爲了方便直接拿來用了。

@RestController
@RequestMapping("user")
public class UserController extends ApiController {

    /**
     * 服務對象
     */
    @Resource
    private UserService userService;

    /**
     * 用戶列表展示
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    @GetMapping("view")
    public ModelAndView view(){
        return new ModelAndView("/user").addObject("modelName","用戶管理模塊");
    }

    /**
     * 新增用戶
     *
     * @param user 用戶實體
     * @return 新增結果
     */
    @PostMapping("insert")
    public R insert(@RequestBody User user){
        Assert.notNull(user,"user不能爲空");
        return success(userService.save(user));
    }

    /**
     * 修改用戶
     *
     * @param user 用戶實體
     * @return 修改結果
     */
    @PostMapping("update")
    public R update(@RequestBody User user){
        Assert.notNull(user,"user不能爲空");
        return success(userService.saveOrUpdate(user));
    }

    /**
     * 刪除用戶
     *
     * @param ids 用戶ids
     * @return 刪除結果
     */
    @PostMapping("delete")
    public R delete(@RequestParam List<String> ids){
        Assert.notNull(ids,"ids不能爲空");
        return success(userService.removeByIds(ids));
    }

    /**
     * 查詢用戶數據 - 分頁
     *
     * @param current 當前頁
     * @param size 頁碼大小
     * @return 分頁數據列表
     */
    @GetMapping("selectAll")
    public R selectAll(@RequestParam Integer current, @RequestParam Integer size, @RequestParam(required = false) String userName){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasText(userName)){
            queryWrapper.like("user_name", userName);
        }
        Page<User> page = new Page<User>(current,size);
        IPage<User> result = userService.page(page, queryWrapper);
        return success(result);
    }
}

6、service服務層

服務層就比較簡單了,直接用的 mybatisplus 的 IService,這個類中實現了大部分方法。直接拿來集成就好了,代碼都不用寫。

public interface UserService extends IService<User> {}

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {}

一個接口,一個實現,沒寫一點代碼。

7、前端界面

前端界面用的 layui,全部代碼就不粘貼了,說一下 Thymeleaf 吧,主要是頭部需要聲明,結構如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>測試</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link rel="stylesheet" type="text/css" th:href="@{/plugins/layui/css/layui.css}"/>
    </head>
    <body>
        <div>測試</div>
    </body>
</html>

本文源碼:https://gitee.com/niceyoo/springboot-thymeleaf-demo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章