SpringBoot整合JDBC以及Thymeleaf模板基础学习(十分钟教会你基础学习!!!)

1.JdbcTemplate

关于SpringData介绍
在这里插入图片描述
Spring Framework对数据库的操作在Jdbc上面做了深层次的封装,通过依赖注入功能,可以将DataSource注册到JdbcTemplate之中,使我们可以轻易的完成对象关系映射,并有助于规避常见的错误,在SpringBoot中我们可以很轻松使用它。
特点:

  1. 速度快,对比其他的ORM框架而言,JDBC的方式无异于是最快的。
  2. 配置简单,Spring自家出品,几乎没有额外的配置
  3. 学习成本低,毕竟JDBC是最基础的知识,JdbcTemplate更像是一个DBUtils

整合JdbcTemplate

在 pom.xml 中添加对 JdbcTemplate 的依赖

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

在 application.properties 中添加如下配置。值得注意的是,SpringBoot默认会自动配置 DataSource ,
它将优先采用 HikariCP 连接池,如果没有该依赖的情况则选取 tomcat-jdbc ,如果前两者都不可用最后选
取 Commons DBCP2 。通过spring.datasource.type属性可以指定其它种类的连接池

# 数据源
spring:
datasource:
url: jdbc:mysql:///boot?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password:

启动项目,通过日志,可以看到默认情况下注入的是 HikariDataSource

2022-11-16 09:14:46.329 INFO 16472 --- [ main]
com.xja.Day03Application : Starting Day03Application using Java
1.8.0_201 on DESKTOP-TTS40QH with PID 16472 (E:\课程记录\T6\03-SpringBoot整合
\day03\target\classes started by lenovo in E:\课程记录\T6\03-SpringBoot整合\day03)
2022-11-16 09:14:46.336 INFO 16472 --- [ main]
com.xja.Day03Application : No active profile set, falling back
to 1 default profile: "default"
2022-11-16 09:14:47.614 INFO 16472 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC
repositories in DEFAULT mode.
2022-11-16 09:14:47.624 INFO 16472 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository
scanning in 5 ms. Found 0 JDBC repository interfaces.
2022-11-16 09:14:48.329 INFO 16472 --- [ main]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080
(http)
2022-11-16 09:14:48.342 INFO 16472 --- [ main]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-11-16 09:14:48.342 INFO 16472 --- [ main]
org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache
Tomcat/9.0.68]
2022-11-16 09:14:48.559 INFO 16472 --- [ main] o.a.c.c.C.[Tomcat].
[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-11-16 09:14:48.560 INFO 16472 --- [ main]
w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext:
initialization completed in 2156 ms
2022-11-16 09:14:48.977 WARN 16472 --- [ main]
ion$DefaultTemplateResolverConfiguration : Cannot find template location:
classpath:/templates/ (please add some templates, check your Thymeleaf
configuration, or set spring.thymeleaf.check-template-location=false)
2022-11-16 09:14:49.090 INFO 16472 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-11-16 09:14:49.283 INFO 16472 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-11-16 09:14:49.586 INFO 16472 --- [ main]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080
(http) with context path ''
2022-11-16 09:14:49.596 INFO 16472 --- [ main]
com.xja.Day03Application : Started Day03Application in 4.047
seconds (JVM running for 7.288)

案例测试

创建一张t_user的表

CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(1) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

实体类

package com.xja.entity;
import lombok.Data;
@Data
public class Student {
    
    
private Integer id;
private String name;
private int age;
private String description;
}

控制层

package com.xja.controller;
import java.util.List;
@Controller
@RequestMapping("/student")
public class StudentController {
    
    
@Autowired
private StudentService studentService;
/**
* 查询
*/
@RequestMapping("queryStudentList")
public String queryStudentList(Model model){
    
    
List<Student> list = studentService.queryStudentList();
model.addAttribute("list",list);
return "student_list";
}
/**
* 增加跳转
*/
@RequestMapping("/toAdd")
public String toAdd(){
    
    
return "student_add";
}
/**
* 增加
*/
@RequestMapping("/saveStudent")
public String saveStudent(Student student){
    
    
studentService.saveStudent(student);
return "redirect:/student/queryStudentList";
}
@RequestMapping("/deleteStudent")
public String deleteStudent(Integer id){
    
    
studentService.deleteStudent(id);
return "redirect:/student/queryStudentList";
	}
}

业务层省略->持久化层

package com.xja.dao;
import java.util.List;
@Repository //老实持久层的标记 同 @Controller @Service 一起的
public class StudentDao {
    
    
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Student> queryStudentList() {
    
    
String sql = "select * from student";
List<Student> list = jdbcTemplate.query(sql, new
BeanPropertyRowMapper<>(Student.class));
return list;
}
//单个对象 queryForObject
public void saveStudent(Student student) {
    
    
String sql = "insert into student (name,age,description) value
(?,?,?)";
jdbcTemplate.update(sql,student.getName(),student.getAge(),student.getDescript
ion());
}
public void deleteStudent(Integer id) {
    
    
String sql = "delete from student where id = ?";
jdbcTemplate.update(sql,id);
	}
}

查询页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
<script type="text/javascript" th:src="@{/js/jquery-3.6.0.js}"></script>
<script type="text/javascript" th:src="@{/js/bootstrap.min.js}"></script>
<script>
$(function () {
      
      
$("#save").click(function () {
      
      
window.location = "toAdd";
})
})
function deletes(id){
      
      
alert(id);
}
</script>
</head>
<body>
<button class="btn btn-success" id="save">增加</button>
<table class="table table-bordered" style="width: 800px">
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>描述</th>
<th>操作</th>
</tr>
<tr th:each="stu,i:${list}">
<td th:text="${i.count}"></td>
<td th:text="${stu.name}"></td>
<td th:text="${stu.age}"></td>
<td th:text="${stu.description}"></td>
<td>
<button class="btn btn-sm btn-danger"
th:onclick="|deletes(${stu.id})|">删除</button>
<a th:href="|deleteStudent?id=${stu.id}|">删除</a>
</td>
</tr>
</table>
</body>
</html>

结果:略

2.Thymeleaf模板

介绍:
Thymeleaf是用来开发Web和独立环境项目的现代服务器端Java模板引擎。
Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板 - HTML。可以在直接浏览器中正确显示,
并且可以作为静态原型,从而在开发团队中实现更强大的协作。
借助Spring Framework的模块,可以根据自己的喜好进行自由选择,可插拔功能组件,Thymeleaf是现代
HTML5 JVM Web开发的理想选择 - 尽管它可以做的更多。
Spring官方支持的服务的渲染模板中,并不包含jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与
SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注
Thymeleaf的语法即可。

特点:

  1. 动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态
    效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html
    标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,
    所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静
    态内容,使页面动态显示。
    2.开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免
    每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
    3.多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的
    实现表单绑定、属性编辑器、国际化等功能。
    4.与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解
    析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区
    别。

基本设置

创建环境
勾选web和Thymeleaf
默认配置
不需要做任何配置,启动器已经帮我们把Thymeleaf的视图解析器配置完成:
在这里插入图片描述
而且,还配置了模板文件(HTML)的位置,与jsp类似的前缀+视图名+后缀风格
在这里插入图片描述
默认前缀: classpath:/templates/
默认后缀: .html

所以如果我们返回视图: users ,会指向到 classpath:/templates/users.html
Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致我们修改页面不会立即被展现,因此我们关
闭缓存:

#关闭Thymeleaf的缓存
spring.thymeleaf.cache=false

另外,修改完毕页面,需要使用快捷键: Ctrl + Shift + F9 来刷新工程。
快速开始
我们准备一个controller,控制视图跳转

@Controller
public class HelloController {
    
    
@GetMapping("show1")
public String show1(Model model){
    
    
model.addAttribute("msg", "Hello, Thymeleaf!");
return "hello";
	}
}

新建一个HTML模板

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1 th:text="${msg}">大家好</h1>
</body>
</html>

注意,把html 的名称空间,改成: xmlns:th=“http://www.thymeleaf.org” 会有语法提示
启动项目,访问页面:
在这里插入图片描述

语法

Thymeleaf的主要作用是把model中的数据渲染到HTML中,因此其语法主要是如何解析model中的数据,从以下方面来学习:

  • 变量

  • 方法

  • 条件判断

  • 循环

  • 运算

     逻辑预算
     布尔运算
     比较运算
     条件运算
    
  • 其他

变量

我们先新建一个实体类:User

public class User {
    
    
String name;
int age;
User friend;// 对象类型属性
}

然后在模型中添加数据

@GetMapping("show2")
public String show2(Model model){
    
    
User user = new User();
user.setAge(21);
user.setName("Jack Chen");
user.setFriend(new User("李小龙", 30));
model.addAttribute("user", user);
return "show2";
}

语法说明:
Thymeleaf通过 ${} 来获取model中的变量,注意这不是el表达式,而是ognl表达式,但是语法非常像。
示例:
我们在页面获取user数据:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户页面</title>
</head>
<body>
<div th:text="${user.name}"></div>
</body>
</html>

结果:略
感觉跟el表达式几乎是一样的。不过区别在于,我们的表达式写在一个名为: th:text 的标签属性中,这个
叫做 指令

动静结合
指令:
Thymeleaf崇尚 自然模板 ,意思就是模板是纯正的html代码,脱离模板引擎,在纯静态环境也可以直接运
行。现在如果我们直接在html中编写 ${} 这样的表达式,显然在静态环境下就会出错,这不符合Thymeleaf
的理念。
Thymeleaf中所有的表达式都需要写在 指令 中,指令是HTML5中的自定义属性,在Thymeleaf中所有指令都
是以 th: 开头。因为表达式 ${user.name} 是写在自定义属性中,因此在静态环境下,表达式的内容会被当
做是普通字符串,浏览器会自动忽略这些指令,这样就不会报错了!
现在,我们不经过SpringMVC,而是直接用浏览器打开页面看看:
在这里插入图片描述

  • 静态页面中, th 指令不被识别,但是浏览器也不会报错,把它当做一个普通属性处理。这样 span 的默 认值 请登录 就会展现在页面
  • 如果是在Thymeleaf环境下, th 指令就会被识别和解析,而 th:text 的含义就是替换所在标签中的文 本内容,于是user.name 的值就替代了 span 中默认的请登录

指令的设计,正是Thymeleaf的高明之处,也是它优于其它模板引擎的原因。动静结合的设计,使得无论是
前端开发人员还是后端开发人员可以完美契合。
向下兼容
但是要注意,如果浏览器不支持Html5怎么办?
如果不支持这种 th: 的命名空间写法,那么可以把 th:text 换成 data-th-text ,Thymeleaf也可以兼容。
escape
另外, th:text 指令出于安全考虑,会把表达式读取到的值进行处理,防止html的注入。
例如,

你好

将会被格式化输出为 l t ; p lt;p lt;pgt;你好 l t ; / p lt;/p lt;/plt; 。
如果想要不进行格式化输出,而是要输出原始内容,则使用 th:utext 来代替.
ognl表达式的语法糖
刚才获取变量值,我们使用的是经典的 对象.属性名 方式。但有些情况下,我们的属性名可能本身也是变量,
怎么办?
ognl提供了类似js的语法方式:
例如: ${
    
    user.name} 可以写作${
    
    user['name']}

自定义变量
场景
看下面的案例:

<h2>
<p>Name: <span th:text="${user.name}">Jack</span>.</p>
<p>Age: <span th:text="${user.age}">21</span>.</p>
<p>friend: <span th:text="${user.friend.name}">Rose</span>.</p>
</h2>

我们获取用户的所有信息,分别展示。
当数据量比较多的时候,频繁的写 user. 就会非常麻烦。
因此,Thymeleaf提供了自定义变量来解决:
示例:

<h2 th:object="${user}">
<p>Name: <span th:text="*{name}">Jack</span>.</p>
<p>Age: <span th:text="*{age}">21</span>.</p>
<p>friend: <span th:text="*{friend.name}">Rose</span>.</p>
</h2>

首先在 h2 上 用 th:object=“${user}” 获取user的值,并且保存然后,在 h2 内部的任意元素上,可以通过 *{属性名} 的方式,来获取user中的属性,这样就省去了大量的
user. 前缀了
方法

<h2 th:object="${user}">
<p>FirstName: <span th:text="*{name.split(' ')[0]}">Jack</span>.</p>
<p>LastName: <span th:text="*{name.split(' ')[1]}">Li</span>.</p>
</h2>

在这里插入图片描述
Thymeleaf提供的全局对象:
在这里插入图片描述

举例
我们在环境变量中添加日期类型对象

@GetMapping("show3")
public String show3(Model model){
    
    
model.addAttribute("today", new Date());
return "show3";
}

页面处理

<p>
今天是: <span th:text="${#dates.format(today,'yyyy-MM-dd')}">2018-04-25</span>
</p>

字面值

有的时候,我们需要在指令中填写基本类型如:字符串、数值、布尔等,并不希望被Thymeleaf解析为变
量,这个时候称为字面值。
字符串字面值
使用一对 ’ 引用的内容就是字符串字面值了:

<p>
你正在观看 <span th:text="'thymeleaf'">template</span> 的字符串常量值.
</p>

th:text 中的thymeleaf并不会被认为是变量,而是一个字符串
数字字面值
数字不需要任何特殊语法, 写的什么就是什么,而且可以直接进行算术运算

<p>今年是 <span th:text="2018">1900</span>.</p>
<p>两年后将会是 <span th:text="2018 + 2">1902</span>.</p>

布尔字面值
布尔类型的字面值是true或false:

<div th:if="true">
你填的是true
</div>

这里引用了一个 th:if 指令,跟vue中的 v-if 类似
运算
算术运算
支持的算术运算符: + - * / %

<span th:text="${user.age}"></span>
<span th:text="${user.age}%2 == 0"></span>
  • 比较运算
    支持的比较运算: > , < , >= and <= ,但是 > , < 不能直接使用,因为xml会解析为标签,要使用别名。
    注意 == and != 不仅可以比较数值,类似于equals的功能。
    可以使用的别名: gt (>), lt (<), ge (>=), le (<=), not (!). Also eq (==), neq/ne (!=).
  • 条件运算
    1.三元运算
 <span th:text="${user.sex} ? '':''"></span>

三元运算符的三个部分:conditon ? then : else
condition:条件
then:条件成立的结果
else:不成立的结果
其中的每一个部分都可以是Thymeleaf中的任意表达式。
2.默认值
有的时候,我们取一个值可能为空,这个时候需要做非空判断,可以使用 表达式 ?: 默认值 简
写:

 <span th:text="${user.name} ?: '二狗'"></span>

当前面的表达式值为null时,就会使用后面的默认值。
注意: ?: 之间没有空格。
循环

循环也是非常频繁使用的需求,我们使用 th:each 指令来完成:
假如有用户的集合:users在Context中。

<tr th:each="user : ${users}">
<td th:text="${user.name}">Onions</td>
<td th:text="${user.age}">2.41</td>
</tr>

${users} 是要遍历的集合,可以是以下类型:

1.Iterable,实现了Iterable接口的类
2.Enumeration,枚举
3.Interator,迭代器
4.Map,遍历得到的是Map.Entry
5.Array,数组及其它一切符合数组结果的对象
在迭代的同时,我们也可以获取迭代的状态对象:

<tr th:each="user,stat : ${users}">
<td th:text="${user.name}">Onions</td>
<td th:text="${user.age}">2.41</td>
</tr>

stat对象包含以下属性:

  • index,从0开始的角标
  • count,元素的个数,从1开始
  • size,总元素个数
  • current,当前遍历到的元素
  • even/odd,返回是否为奇偶,boolean值
  • first/list,返回值是否为第一或最后,Boolean值
    逻辑判断

有了 if和else ,我们能实现一切功能_
Thymeleaf中使用 th:if 或者 th:unless ,两者的意思恰好相反。

<span th:if="${user.age} < 24">小鲜肉</span>

如果表达式的值为true,则标签会渲染到页面,否则不进行渲染。
以下情况被认定为true:
表达式值为true
表达式值为非0数值
表达式值为非0字符
表达式值为字符串,但不是 “false” , “no” , “off”
表达式不是布尔、字符串、数字、字符中的任何一种
其它情况包括null都被认定为false

猜你喜欢

转载自blog.csdn.net/weixin_52859229/article/details/129764393