Spring Boot Thymeleaf H2数据库CRUD示例

Thymeleaf + Spring Boot - Complete Tutorial (Step by Step with Source Codes) - Kindson The Geniushttps://www.kindsonthegenius.com/thymeleaf-spring-boot-complete-tutorial-step-by-step-with-source-codes/

 

1. Thymeleaf 简介 (视频)

在本演练中,我们将构建一个应用程序来存储学生记录。用户将能够:

  • 在 html 页面中访问学生列表
  • 添加新学生
  • 更新学生
  • 删除学生

我们将学习以下技术:

  • Spring Boot
  • JPA 存储库
  • H2 内存数据库
  • Thymeleaf 
  • Javascript、Bootstrap 和 JQuery
  • 和更多!

什么是Thymeleaf Thymeleaf 是一个用于处理页面(HTML5、XML、XHTML)的服务器端模板引擎

要安装的东西:

MySQL – 免费社区版可以从这里获得

Spring Tool Suite – 从这里免费下载

 

2. Spring Initializr 中的项目设置 (视频)

转到 start.spring.io 并创建一个项目。使用以下设置:

  • 项目:Maven 项目
  • 语言:Java
  • Spring Boot:2.1.6
  • 组:com.kindsonthegenius(你可以改变这个)
  • Artifact:thymeleaf-app
  • 名称: thymeleaf-app
  • 描述:Thymeleaf Application
  • 包名:com.kindsonthegenius.thymeleaf-app
  • 包装:Jar
  • 爪哇:8

添加以下依赖项:H2 Database、MySql Driver、Spring Data JPA、Thymeleaf、Spring web starter

生成了项目。所以项目被下载为 zip 文件

解压文件并在 Spring Tool Suite 中打开

 

3. 添加其他依赖项 (视频)

打开 pom.xml 文件以确保指定了依赖项

添加以下附加依赖项:

  • spring-web
  • spring-context
  • Bootstrap (4.3.1)
  • JQuery (3.4.1)

此依赖项来自Maven 存储库

从 spring-web 和 spring-context 中删除版本标签

保存项目

 

通用架构或我们的应用程序如下所示

 

4. 创建一个 html 并测试 Thymeleaf  (视频)

在 com.kindsonthegenius.thymeleafapp 包中创建一个名为 HomeController 的类

使用 @Controller 注解对此类进行注解

编写一个名为 test 的 String 方法以返回“索引”。

使用 @RequestMapping(“/home”) 注释此方法

HomeController.java文件内容如下图

@Controller
public class HomeController {
	
	@RequestMapping("/home")
	public String test() {
		return "index";
	}
}

 

在模板文件夹中创建一个 html 文件。模板文件夹位于 src/main/resources 文件夹内。

html文件内容如下图

运行应用程序

然后访问 http://localhost:8080/home 并确保页面显示

 

5. 设置和测试 H2 数据库 (视频)

打开 application.properties 文件并添加以下指令

spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:studentdb
spring.jpa.hibernate.ddl-auto=update

 

运行应用程序

然后访问 http://localhost:8080/h2-console

确保数据库的名称是 studentdb

然后点击连接。您现在将看到 h2 控制台打开。

 

6. 设置 MySQL 数据库 (视频)

再次打开 application.properties 文件

添加以下代码来配置 MySQL 数据源

请注意,H2 数据库的数据源配置已被注释掉。这是因为您可以同时拥有两个数据源

#H2 Database Configuration
#spring.h2.console.enabled=true
#spring.datasource.platform=h2
#spring.datasource.url=jdbc:h2:mem:studentdb
#spring.jpa.hibernate.ddl-auto=update

#MySQL Database Configuration
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.password=root
spring.datasource.username=root
spring.datasource.url=jdbc:mysql://localhost:3307/student
spring.jpa.hibernate.ddl-auto=update
spring.datasource.initialization-mode=always

#if you receive Timezone error, then replace the datasource url with the one below
#spring.datasource.url=jdbc:mysql://localhost:3301/student?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

 

7. 创建模型(学生类)  (视频)

在模型包中创建一个名为 Student 的类

该类应具有以下成员变量:

  • 标识(整数)
  • 名称(字符串)
  • 部门(字符串)
  • 更新者(字符串)
  • 更新日期(日期

使用 @Entity 注解对类进行注解

使用 @Id 注解对 Id 字段进行注解

使用 @DataTimeFormat(pattern=”yyyy-MM-dd”) 注解对 updatedOn 字段进行注解

该类将如下所示

 

@Entity
public class Student {
	
	@Id
	private Integer Id;
	private String name;
	private String department;
	private String updatedBy;
	
	@DateTimeFormat(pattern="yyyy-MM-dd")
	private String updatedOn;
}

 

生成构造函数、getter 和 setter 以及 toString 方法

 

8.编写并测试数据库初始化查询 (视频)

在 src/main/resources 文件夹中创建一个名为 data.sql 的文件

写一个查询插入一些初始数据。该文件的内容如下所示;

insert into student values(1, 'Kindson Munonye', 'Computer Science', 'The Tech Pro', '2019-06-27');
insert into student values(2, 'Kate Winston', 'Managment', 'The Tech Pro', '2019-06-27');
insert into student values(3, 'Solace Okeke', 'Data Science', 'The Tech Pro', '2019-06-27');

 

现在,测试应用程序。

首先,检查在mySQL服务器中创建了Student表并插入了数据

接下来,对H2数据库做同样的事情

请记住在测试每个数据库之前修改 application.properties 文件;

 

9. 创建原始存储库 (视频)

在 repositories 文件夹中创建一个名为 StudentRepository 的接口

使这个接口扩展 CrudRepository

分别指定class和Id类型为Student和Integer

使用 @Repository 注解对类进行注解

 

10. 创建业务服务 (视频)

在 services 文件夹中创建一个名为 StudentService 的类

使用 @Service 注释对此类进行注释

将 StudentRepository 自动连接到 StudentService

 

11. 创建控制器 (视频)

创建一个名为 StudentController 的类

使用 @Controller 注解对类进行注解

用 @RequestMapping(“/students”) 注释这个类

将 StudentService 自动连接到 StudentController

 

12. 编写 getAll() 方法 (视频)

在 StudentService 中,编写一个 GetAll 方法。此方法应调用存储库的 findAll() 方法。

此方法应返回 List<Student>

在 StudentController 中, 编写getAll方法。这个方法应该调用服务的getAll方法

使用 @RequestMapping(“/getAll”) 注释此方法

此方法应返回一串“学生

代码如下所示

@RequestMapping("/getAll")
public String getAll(Model model) {
	List<Student> students = studentService.getAll();
	model.addAttribute("students", students);
	return "students";
}

 

13. 设置和测试 html 页面 (视频)

确保 StudentController 可以使用 Thymeleaf 提供页面;

在模板文件夹中创建一个 html 页面并将其命名为students.html

在页面上写一些文字。

继续运行应用程序。

导航到 http://localhost:8080/students/getAll。确认html页面显示

可选:将@Controller 注解更改为@RestController。还要修改函数以返回 List<Student>。然后测试它是否真的返回数据。

 

14. 设置 Bootstrap 和 JQuery  (视频)

在 html 页面中,包含在标题部分中:

  • bootstrap.css 的链接
  • jquery.js 脚本
  • bootstrap.js 脚本

对我来说,如下图所示:

<link href="/webjars/bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet" />
<script type="text/javascript" src="/webjars/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/webjars/jquery/3.4.1/jquery.min.js"></script>

创建一个简单的表并使用 table table-stripped 类对其进行测试

注意:如果链接和脚本不起作用,请尝试使用网站上的 CDN 链接

 

15. 将数据从控制器发送到视图 (视频)

修改控制器中的getAll方法,添加一个模型对象作为参数

现在调用该服务以返回学生列表。

然后将此列表作为属性分配给模型对象。这样,该列表将在视图中可用。

该方法将如下所示:

@RequestMapping("/getAll")
public String getAll(Model model) {
	List<Student> students = studentService.getAll();
	model.addAttribute("students", students);
	return "students";
}

 

16.在View(html页面)中接收数据 (视频)

将html页面中的表格修改为五列两行。

然后添加 Thymeleaf 标记以显示来自模型的数据。

最终表如下所示

<table class="table table-stripped">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Department</td>
<td>Updated By</td>
<td>Updated On</td>
</tr>
</thead>
<tr th:each="student:${students}">
<td th:text="${student.Id}">Id</td>
<td th:text="${student.name}">Name</td>
<td th:text="${student.department}">Department</td>
<td th:text="${student.updatedBy}">Updated By</td>
<td th:text="${student.updatedOn}">Updated On</td>
</tr>
</table>

 

运行应用程序并检查数据是否显示在页面中

 

17. 编写并测试 getOne() 方法 (视频)

在 Service 类中,编写方法 getOne() 以返回单个记录。

在Controller类中,编写getOne()方法

它将返回一个学生。此外,它需要一个整数参数 Id。

使用 @RequestMapping(“/getOne”) 注释此方法

此时,控制器中的 getOne 方法如下所示:

@RequestMapping("/getOne") 
@ResponseBody
public Optional<Student> getOne(Integer Id)
{
	return studentService.getOne(Id);
}

 

18. 编写 addNew 方法 (视频)

在 StudentService 中,编写 addNew 方法。

此方法将获取一个 Student 对象并将其保存到存储库中。

在 StudentController 中,编写 addNew 方法

使用 @RequestMapping(value=”/addNew” method=”post”) 注释该方法

@PostMapping(value="/addNew")
public String addNew(Student student) {
	studentService.addNew(student);
	return "redirect:/students/getAll";
}

注意:重定向语句中没有空格!

 

19. 设置 AddModal 对话框 (视频)

最简单的方法是访问 Bootstrap 网站并获取模态表单模板。复制代码并将其添加到students.html 页面。

也复制按钮的代码

将 form 标签移动到最上层的 div 标签!

修改添加按钮中的名称和文本。

然后修改表单以添加文本字段。

将文本字段的 ID 更改为相关的内容。

测试应用程序以查看外观

 

20. 完成并测试插入操作 (视频)

提供与模型中使用的名称相对应的文本字段名称属性。

将保存操作的按钮类型从“按钮”更改为“提交”

将表单的 th:action 设置为 @”{/students/addNew}”。

设置发布方法

测试应用程序并尝试将数据插入数据库。如果有效,恭喜!

如果没有,请观看视频并给我留言,让我知道,以便我为您提供帮助。

 

21. 编写更新方法 (视频)

在学生服务中,编写更新方法。此方法应调用存储库的 save() 方法。

此外,在 Controller 中,编写更新方法。

此方法采用 Student 的单个参数。

用@RequestMapping 注释这个方法……。

它返回一个重定向到 students/findAll url

控制器的最终 update() 方法如下所示

@RequestMapping(value="/update", method = {RequestMethod.PUT, RequestMethod.GET})
public String update(Student student) {
	studentService.update(student);
	return "redirect:/students/getAll";
}

 

22. 设置编辑模式 (视频)

最简单的方法是复制现有的 addModal。然后把名字改成editModal

将文本字段的名称更改为相关的名称

像这样设置editModal的动作——th:action = “@{/students/update}”

现在,在表格中,添加第六列并将其命名为 Edit。

然后添加一个按钮并将其 data-target 属性设置为#editModal(我们稍后将其更改为链接)

将此按钮的类别设置为“btn btn-warning”

测试应用程序以确保模态显示

然后将按钮更改为锚标记

 

23. 创建自定义 js 文件 (视频)

现在,如果您测试应用程序,您将看到当我们单击“编辑”按钮时没有任何反应。我们将编写一个在单击按钮时运行的自定义脚本。

在 src/main/resources 的静态文件夹中,创建一个文件夹 js。

然后创建一个名为 main.js 的文件。

在students.html 页面的head 部分中添加指向该文件的链接。链接如下:

<script type="text/javascript" src="../static/js/main.js" th:src="@{/js/main.js}"></script>

注意:确保正确处理!

在这个文件中,编写一个函数来显示editModal。该文件如下所示:

 

$('document').ready(function(){	
	$('.table #editButton').on('click',function(event){	
		
		event.preventDefault();
		
		$('#editModal').modal();				
	});	
});

注意:“点击”和功能之间没有空格

注意: event.preventDefault() 会阻止链接导航到响应页面。尝试将其删除并重新运行应用程序,以便了解它是如何工作的。

然后测试应用程序并确保显示 editModal 表单

 

24. 完成并测试编辑方法 (视频)

单击editButton时应该做两件事:

  • 请求被发送到 /students/getOne?Id={Id} 以检索特定记录
  • 检索到的值分配给编辑文本字段

将 href 属性添加到 editButton。属性如下图:

th:href="@{/students/getOne/(Id=${student.Id})}"

 

现在修改main.js文件。编写代码以将学生记录的值分配给文本字段。最后的最终代码将是:

 

25. 编写删除方法 (视频)

在 studentService 中编写删除方法。

还要在StudentController文件中写delete方法

delete 方法将采用参数,即要删除的记录的 ID。

delete() 方法如下所示:

@RequestMapping(value="/delete", method = {RequestMethod.DELETE, RequestMethod.GET})	
public String delete(Integer Id) {
	studentService.delete(Id);
	return "redirect:/students/getAll";
}

 

26. 设置删除模式 (视频)

现在添加和更新运行良好,我要恭喜你!

要添加删除,我们将使用引导网站中的模式。

将模态框放在页面中,并给它一个 deleteModal 的 id

将其上的文本更改为相关的内容。

将按钮更改为锚标记并将 href 设置为“”

在表中添加删除链接,就像编辑链接一样,但这次添加到 /delete 端点

修改main.js文件显示deleteModal

测试应用程序并检查模式是否显示。

 

27. 完成并测试删除模式 (视频)

现在给 deleteModal 中的按钮一个 delRef 的 id

在main.js文件中,编写代码完成删除操作

deleteButton的js代码如下所示:

$('.table #deleteButton').on('click',function(event){
	event.preventDefault();		
	var href = $(this).attr('href');
	$('#deleteModal #delRef').attr('href', href);		
	$('#deleteModal').modal();
});

测试应用程序以确保其正常工作。

 

28. 使用 Thymeleaf 显示登录的用户名 (视频)

用户身份验证和授权包含在 Spring Security 中。我目前正在编写有关 Spring Security 的教程,并将在接下来的几天内发布。

目前,将登录用户详细信息传递给视图的最简单方法是将其放置在模型中。这可以在 getAll 函数中完成,因为这是我们正在使用的唯一页面。

只需在 getAll() 方法中编写这一行代码:

String username = "Kindson";
model.addAttribute("username", username);

 

然后在 students.html 页面中,您可以使用以下代码检索该值:

Welcome,  <span th:text="${username}">Welcome guest!

 

29. 为 UI 使用 BootStrap

 GitHub - KindsonTheGenius/ThymeleafApphttps://github.com/KindsonTheGenius/ThymeleafApp

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值