SpringBoot integrates JDBC and Thymeleaf template basic learning (teach you basic learning in ten minutes!!!)

1.JdbcTemplate

Introduction to SpringData
insert image description here
The Spring Framework's operations on the database are deeply encapsulated on Jdbc. Through the dependency injection function, the DataSource can be registered in the JdbcTemplate, so that we can easily complete the object-relational mapping and help to avoid common Error, we can use it easily in SpringBoot.
Features:

  1. The speed is fast. Compared with other ORM frameworks, the JDBC method is the fastest.
  2. Simple configuration, produced by Spring itself, almost no additional configuration
  3. Low learning cost, after all JDBC is the most basic knowledge, JdbcTemplate is more like a DBUtils

Integrate JdbcTemplate

Add a dependency on JdbcTemplate in pom.xml

<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>

Add the following configuration in application.properties. It is worth noting that SpringBoot will automatically configure DataSource by default.
It will give priority to HikariCP connection pool. If there is no such dependency, select tomcat-jdbc. If the former two are not available, finally select
Commons DBCP2. Other types of connection pools can be specified through the spring.datasource.type property

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

Start the project, through the log, you can see that HikariDataSource is injected by default

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)

case test

Create a t_user table

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;

Entity class

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

control layer

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";
	}
}

Business layer omitted -> persistence layer

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);
	}
}

query page

<!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>

Result: slightly

2. Thymeleaf template

Introduction:
Thymeleaf is a modern server-side Java template engine for developing web and standalone environment projects.
The main goal of Thymeleaf is to bring the elegance of natural templating - HTML to your development workflow. Can be displayed correctly in the direct browser
and can be used as a static prototype, allowing for stronger collaboration among development teams.
With Spring Framework's modules, free to choose as you like, and pluggable functional components, Thymeleaf is
ideal for modern HTML5 JVM web development - although it can do much more.
The rendering template of services officially supported by Spring does not contain jsp. It is Thymeleaf and Freemarker, etc., and
the integration of Thymeleaf with SpringMVC's view technology and SpringBoot's automatic configuration is perfect, and there is almost no cost. You only need to pay attention to
Thymeleaf's syntax.

Features:

  1. Combination of dynamic and static: Thymeleaf can run in both networked and non-networked environments, that is, it allows artists to view the static
    effect of the page in the browser, and allows programmers to view the dynamic page effect with data on the server. This is because it supports html prototypes, and then
    adds additional attributes in html tags to achieve template + data display. When the browser interprets html, it ignores undefined tag attributes,
    so the template of thymeleaf can run statically; when some data is returned to the page, the Thymeleaf tag will dynamically replace the static
    content, so that the page can be displayed dynamically.
    2. Out-of-the-box: It provides standard and spring standard dialects, and can directly apply templates to achieve JSTL and OGNL expression effects, avoiding the
    troubles of templates, jstl, and label changes every day. At the same time, developers can also extend and create custom dialects.
    3. Multi-dialect support: Thymeleaf provides spring standard dialects and an optional module perfectly integrated with SpringMVC, which can quickly
    realize functions such as form binding, attribute editor, and internationalization.
    4. Perfect integration with SpringBoot, SpringBoot provides the default configuration of Thymeleaf, and set up a view parser for Thymeleaf
    , we can operate Thymeleaf as we used to operate jsp. There is hardly any difference in code except in the template syntax
    .

basic settings

Create environment Check the default configuration of
web and Thymeleaf No need to do any configuration, the launcher has helped us configure Thymeleaf's view parser: Moreover, it also configures the location of the template file (HTML), a prefix similar to jsp + view name +Suffix style Default prefix: classpath:/templates/ Default suffix: .html


insert image description here

insert image description here

So if we return to the view: users , it will point to classpath:/templates/users.html
Thymeleaf will enable page caching by default to improve page concurrency. But it will cause our modified page to not be displayed immediately, so we close
the cache:

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

In addition, after modifying the page, you need to use the shortcut key: Ctrl + Shift + F9 to refresh the project.
Quick start
Let's prepare a controller to control the view jump

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

Create a new HTML template

<!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>

Note, change the namespace of html to: xmlns:th="http://www.thymeleaf.org" There will be syntax prompts
Start the project and visit the page:
insert image description here

grammar

The main function of Thymeleaf is to render the data in the model into HTML, so its syntax is mainly how to parse the data in the model, learn from the following aspects:

  • variable

  • method

  • conditional judgment

  • cycle

  • operation

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

variable

Let's create a new entity class first: User

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

Then add data to the model

@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";
}

Grammar description:
Thymeleaf uses ${} to obtain variables in the model. Note that this is not an el expression, but an ognl expression, but the syntax is very similar.
Example:
We get user data on the page:

<!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>

Result:
It feels almost the same as the el expression. But the difference is that our expression is written in a tag attribute named: th:text, which
is called a directive

Combination of dynamic and static
Instructions:
Thymeleaf advocates natural templates, which means that templates are pure html codes, which are separated from the template engine and can be run directly in a purely static environment
. Now if we directly write an expression like ${} in html, it will obviously go wrong in a static environment, which is not in line with Thymeleaf's
philosophy.
All expressions in Thymeleaf need to be written in directives, which are custom attributes in HTML5, and all directives in Thymeleaf
start with th:. Because the expression ${user.name} is written in a custom attribute, in a static environment, the content of the expression will be
treated as an ordinary string, and the browser will automatically ignore these instructions, so that no error will be reported !
Now, instead of going through SpringMVC, we open the page directly with a browser to see:
insert image description here

  • In static pages, the th command is not recognized, but the browser will not report an error, and treat it as a normal attribute. In this way, the default value of the span, please log in, will be displayed on the page
  • If it is in the Thymeleaf environment, the th command will be recognized and parsed, and the meaning of th:text is to replace the text content in the label, so the value of user.name replaces the default please login in the span

The design of the instruction is exactly the brilliance of Thymeleaf, and it is also the reason why it is superior to other template engines. The combination of static and dynamic design makes it a perfect fit for both
front-end developers and back-end developers.
Downward Compatibility
But pay attention, what if the browser does not support Html5?
If you do not support this th: namespace, you can replace th:text with data-th-text, and Thymeleaf is also compatible.
In addition, for security
reasons, the th:text command will process the value read by the expression to prevent HTML injection.
For example,

Hello

will be formatted as lt ; p lt;plt;p gt;hello lt;/p lt;/plt;/ p lt; .
If you want to output the original content instead of formatted output, use th:utext instead. Syntactic
sugar of ognl expression
Just now to get the variable value, we used the classic object. Property name method. But in some cases, our attribute name may itself be a variable,
what should we do?
ognl provides a syntax similar to js:
例如: ${
    
    user.name} 可以写作${
    
    user['name']}

Custom variable
scenario
See the following case:

<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>

We get all the information of the user and display them separately.
When the amount of data is relatively large, it will be very troublesome to write user. frequently.
Therefore, Thymeleaf provides custom variables to solve:
Example:

<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>

First use th:object="${user}" on h2 to get the value of user, and save it. Then, on any element inside h2, you can get the attribute in user by *{attribute name}, like this It saves a lot of
user. prefixed
methods

<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>

insert image description here
Global objects provided by Thymeleaf:
insert image description here

For example,
we add a date type object to the environment variable

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

page processing

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

literal value

Sometimes, we need to fill in basic types such as string, value, Boolean, etc. in the command, and we don't want Thymeleaf to parse it into a variable
, which is called a literal value at this time.
String literals
Use a pair of ' to quote content that is a string literal:

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

Thymeleaf in th:text is not considered a variable, but a string
Number literal value
Numbers do not need any special syntax, what is written is what it is, and arithmetic operations can be performed directly

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

Boolean literals
Boolean literals are either true or false:

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

A th:if instruction is quoted here, which is similar to v-if in vue.
Arithmetic
operations
Supported arithmetic operators: + - * / %

<span th:text="${user.age}"></span>
<span th:text="${user.age}%2 == 0"></span>
  • Comparison operations
    Supported comparison operations: > , < , >= and <= , but > , < cannot be used directly, because xml will be parsed as tags and aliases must be used.
    Note that == and != can not only compare values, similar to the function of equals.
    Aliases that can be used: gt (>), lt (<), ge (>=), le (<=), not (!). Also eq (==), neq/ne (!=).
  • Conditional operation
    1. Ternary operation
 <span th:text="${user.sex} ? '':''"></span>

The three parts of the ternary operator: conditon ? then : else
condition: condition
then: the result of the condition being true
else: the result of not being true
Each of these parts can be any expression in Thymeleaf.
2. Default value
Sometimes, we take a value that may be empty. At this time, we need to make a non-empty judgment. You can use the expression?: Abbreviation for default value
:

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

When the previous expression value is null, the latter default value will be used.
Note: There is no space between ?: .
cycle

Loop is also a very frequently used requirement, we use the th:each command to complete:
if there is a collection of users: users are in the Context.

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

${users} is the collection to traverse and can be of the following types:

1.Iterable, a class that implements the Iterable interface
2.Enumeration, an enumeration
3.Interator, an iterator
4.Map, what is traversed is a Map.Entry
5.Array, an array and all other objects that conform to the result of the array are
iterated at the same time , we can also get the iterated state object:

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

The stat object contains the following properties:

  • index, the index starting from 0
  • count, the number of elements, starting from 1
  • size, the total number of elements
  • current, the currently traversed element
  • even/odd, returns whether it is odd or even, boolean value
  • first/list, whether the return value is the first or last, Boolean value
    logic judgment

With if and else, we can achieve all functions_ .
Use th:if or th:unless in Thymeleaf, the meaning of the two is exactly the opposite.

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

If the expression evaluates to true, the label will be rendered to the page, otherwise it will not be rendered.
The following conditions are considered true:
the expression value is true,
the expression value is a non-zero value,
the expression value is a non-zero character
, the expression value is a string, but not "false", "no", "off"
The expression is not a Boolean Any one of , string, number, character,
other conditions including null are considered false

Guess you like

Origin blog.csdn.net/weixin_52859229/article/details/129764393