今日目标

  1. 简单介绍后端渲染模板Thymeleaf,并且在SpringBoot上完成部署和简单测试。
  2. 简单介绍Mybatis框架,并且在SpringBoot上完成配置and简单测试。

概念介绍

什么是Thymeleaf?

能学习SpringBoot的读者,相信一定有JSP的基础,至少知道JSP的概念。

Thymeleaf就是在SpringBoot中可以使用的JSP。

为了快速可靠的开发web(其实是我不怎么会Vue),这套博文不涉及到前后端分离,前端界面用Thymeleaf完成。

Thymeleaf部署在HTML界面中,即使在没有后端渲染的情况下也可以显示,通过SpringBoot中的Controller可以渲染显示出数据。

什么是Mybatis?

能使用SpringBoot的读者,相信至少写过一些啰嗦的JDBC代码。

一句话概括Mybatis——

Mybatis就是封装了对数据库的操作,让你专注的使用SQL语句,当然这种方便需要付出一点点配置的代价。

如何在SpringBoot中部署Mybatis和Thymeleaf?

很简单!

因为SpringBoot是一个Maven项目,可以完成快速简单的配置。

只需要在pom.xml中添加相应的dependency,并且在application.properties文件中添加相应配置语句,就可以在SpringBoot中完成对Mybatis和Thymeleaf的部署了。

IDEA实际操作

部署Thymeleaf

第一步:打开SpringBoot实操(1)中那个部署好的SpringBoot项目,就是一个非常简单的,在localhost:8080/test输出Hello SpringBoot的简单demo。

image.png

第二步:在pom.xml文件中添加Thymeleaf的dependency。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

image.png

第三步:借助Thymeleaf框架编写HTML代码。

PS:其实Thymeleaf说白了,就是一个给后端用的做页面的框架,语法规定的挺复杂,但是我用起来就是那么几个功能,主要是用th代替了很多东西。

在src/main/resources/templates下新建testthymeleaf.html文件。

testthymeleaf.html中的代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>test_thymeleaf</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <p><span th:text="&#39;thymeleaf text&#39;">default text</span></p>
        <input id="id1" name="name1" value="0" th:id="${th_id}" th:name="${th_name}" th:value="${th_value}"/>
    </body>
</html>

image.png

testthymeleaf.html界面可以在浏览器中直接显示,效果如下(未被后端渲染):

image.png

消除testthymeleaf.html中的未声明变量错误:

image.png

第四步:编写TestThymeleafController代码。

接下来我们就要使用后端对HTML代码进行渲染了。

新建src/main/java/com/example/demo/controller/TestThymeleafController.java

代码如下:

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class TestThymeleafController {
    @GetMapping("/testthymeleaf")
    public String TestThymeleaf(ModelMap map){
        map.put("th_id","id2");
        map.put("th_name","name2");
        map.put("th_value",1);
        //这里返回的字符串一定要是HTML文件的名称,这样才能正好映射到。
        return "testthymeleaf";
    }
}

PS:在这里,HTML的文件名如果是simple.html,Controller的名字就要是SimpleController,对应的页面就要是/simple,返回的字符串就要是“simple”,这就是SpringBoot的约定俗成。

启动项目,输入localhost:8080/testthymeleaf查看渲染效果:

image.png

会发现前端页面的内容已经被TestThymeleafController.java中的代码修改了。

部署Mybatis

前面说了,SpringBoot的配置非常的简单,只要修改property和xml文件就可以了。

但是需要注意一点,Mysql数据库是必须的,毕竟Mybatis不是数据库而只是集成框架,所以还需要配置JDBC和MySQL驱动。

第一步:下载数据库并且安装可视化界面,有可视化界面看起来舒服一些,数据库的安装和版本要求,可以参考How2J的MySQL数据库

我本机电脑上配置如下:

image.png

image.png

第二步:打来一个简单的SpringBoot工程,配置pom.xml。

添加依赖如下:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

image.png

PS:注意Mybatis的版本号不能少,我在这里被坑了。

第三步:增加Mybatis的Mapper文件夹并且在application.properties指向Mapper,具体如下:

添加Mapper路径到application.properties中。

mybatis.mapper-locations=classpath:mapper/*Dao.xml

再继续添加本机数据库的各种信息到application.properties中。

# datasource config
spring.datasource.url=jdbc:mysql://localhost:3306/testspringboot2_database?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=admin

PS:注意数据库url连接中关于时区的坑,我被坑了。

所有的application.properties配置

第四步:在MySQL的数据库中(我的是testspringboot2_database)创建表,并且在SpringBoot工程中建立相应的实体类和数据库增删改查接口,然后再在mapper/*dao.xml中实现接口。

建表语句:

DROP TABLE IF EXISTS `tb_user`;

CREATE TABLE `tb_user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT &#39;主键&#39;,
  `name` VARCHAR(100) NOT NULL DEFAULT &#39;&#39; COMMENT &#39;登录名&#39;,
  `password` VARCHAR(100) NOT NULL DEFAULT &#39;&#39; COMMENT &#39;密码&#39;,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

表结构

在SpringBoot工程中新建src/main/java/com/example/demo/entity/User.java实体类。

package com.example.demo.entity;

public class User {
    private Integer id;
    private String name;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

在SpringBoot工程中新建src/main/java/com/example/demo/dao/UserDao.java,完成数据库增删改查接口,具体接口实现不是在UserDao.java中,而是在src/main/resources/mapper/UserDao.xml中。

UserDao.java代码:

package com.example.demo.dao;

import com.example.demo.entity.User;
import java.util.List;

public interface UserDao {
    List<User> findAllUsers();

    int insertUser(User User);

    int updUser(User User);

    int delUser(Integer id);
}

UserDao.xml代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.UserDao">
    <resultMap id="UserResult" type="com.example.demo.entity.User">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="password" column="password"/>
    </resultMap>
    <select id="findAllUsers" resultMap="UserResult">
        select id,name,password from tb_user
        order by id desc
    </select>
    <insert id="insertUser" parameterType="com.example.demo.entity.User">
        insert into tb_user(name,password)
        values(#{name},#{password})
    </insert>
    <update id="updUser" parameterType="com.example.demo.entity.User">
        update tb_user
        set
        name=#{name},password=#{password}
        where id=#{id}
    </update>
    <delete id="delUser" parameterType="int">
        delete from tb_user where id=#{id}
    </delete>
</mapper>

第五步:向启动类DemoApplication.java中添加MapperScan,扫描dao中的增删改查接口。

@MapperScan("com/example/demo/dao")

启动类

第六步:测试SpringBoot中Mybatis的表现。

插入

查询全部

更新

删除

总结

  • 今天测试了Thymeleaf和Mybatis在SpringBoot中的配置。但是其实写的很简单,我还是倾向于在具体的项目中更进一步了解。
  • 明天会在SpringBoot项目中用一下LayUI框架,毕竟页面不能太丑、
  • 在经历了Mybatis的mapper.xml的配置后,却还是感觉在重复的写增删改查?没关系,MybatisGenerator让开发者更加简洁。

就酱紫。

如果图片无法加载,请访问我的原博客