Java学习笔记-Day83 Spring Boot框架(三)
一、Thymeleaf的使用
1、Thymeleaf链接静态资源
(1)在pom.xml文件的build标签中加入使用的静态资源。
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>static/**</include>
<include>**/*.properties</include>
<include>**/*.html</include>
</includes>
</resource>
</resources>
(2)将css、js等静态文件放到static的目录下。
(3)html页面上使用@标记引入静态资源(@代表根目录、绝对路径)。
- 引入css文件:
<link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.css}">
- 引入js文件:
<script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
(4)使用 Ctrl+Shift+F9 重载html。
2、each循环
(1)第一种方式
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.css}">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="container">
<table border="1" class="table table-bordered table-hover">
<thead>
<tr>
<th>用户编号</th>
<th>用户名称</th>
<th>用户电话</th>
<th>用户年龄</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${userlist2}">
<td th:text="${user.userid}"></td>
<td th:text="${user.username.substring(0,2)}"></td>
<td th:text="${user.userphone}"></td>
<td th:text="${user.userage}"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
(2)第二种方式:th:object="${user}"
获取user的值并保存,任意元素可以通过 *{属性名}
的方式来获取user中的属性,这种方式省去了大量的user.前缀。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.css}">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="container">
<table border="1" class="table table-bordered table-hover">
<thead>
<tr>
<th>用户编号</th>
<th>用户名称</th>
<th>用户电话</th>
<th>用户年龄</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${userlist2}" th:object="${user}">
<td th:text="*{userid}"></td>
<td th:text="*{username.substring(0,2)}"></td>
<td th:text="*{userphone}"></td>
<td th:text="*{userage}"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
注意:ognl表达式支持方法调用。
<td th:text="*{username.substring(0,2)}"></td>
<td th:text="${user.username.substring(0,2)}"></td>
2、Thymeleaf内置对象
Thymeleaf中提供了一些内置对象,并且在这些对象中提供了一些方法,方便我们来调用。获取这些对象,需要使用 #对象名
来引用。
- 环境相关对象
对象 | 作用 |
---|---|
#ctx | 获取Thymeleaf自己的Context对象 |
#requset | 如果是web程序,可以获取HttpServletRequest对象 |
#response | 如果是web程序,可以获取HttpServletReponse对象 |
#session | 如果是web程序,可以获取HttpSession对象 |
#servletContext | 如果是web程序,可以获取HttpServletContext对象 |
案例
- UserController.java
package com.etc.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpSession;
@Controller
public class UserController {
@GetMapping("api/user/session")
public String getUserSession(HttpSession session){
session.setAttribute("username","tom");
return "userinfo";
}
}
- userinfo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${#session.getAttribute('name')}"></div>
<div th:text="${session.name}"></div>
</body>
</html>
3、Thymeleaf全局对象
对象 | 作用 |
---|---|
#dates | 处理java.util.date的工具对象 |
#calendars | 处理java.util.calendar的工具对象 |
#numbers | 用来对数字格式化的方法 |
#strings | 用来处理字符串的方法 |
#bools | 用来判断布尔值的方法 |
#arrays | 用来护理数组的方法 |
#lists | 用来处理List集合的方法 |
#sets | 用来处理set集合的方法 |
#maps | 用来处理map集合的方法 |
案例
- UserController.java
package com.etc.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpSession;
import java.util.Date;
@Controller
public class UserController {
@GetMapping("api/user/session")
public String getUserSession(HttpSession session){
session.setAttribute("day",new Date());
return "userinfo";
}
}
- userinfo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${session.day}"></div>
<div th:text="${#dates.format(session.day,'yyyy-MM-dd')}"></div>
</body>
</html>
二、yml文件
1、简介
Spring Boot全局配置文件(在src/main/resources目录中):application.properties、 application.yml。
yml是YAML(YAML Ain’t Markup Language)语言的文件,以数据为中心,比json、xml等更适合做配置文件。
2、基本语法
YAML基本语法:使用缩进表示层级关系,缩进时不允许使用Tab键,只允许使用空格。缩进的空格数目不重要,只要相同层级的元素左侧对齐即可。大小写敏感。在冒号 :
与值之间存在一个空格。
YAML 支持的三种数据结构:
- 常见普通值:单个的、不可再分的值。
- 对象:键值对的集合。
- 数组:一组按次序排列的值。
3、yml文件的使用
(1)在pom.xml文件的includes标签中加入yml文件的静态资源。
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>static/**</include>
<include>**/*.properties</include>
<include>**/*.html</include>
<include>**/*.yml</include>
</includes>
</resource>
</resources>
(2)在\src\main\resources目录中创建application.yml。
author:
id: 1
name: 'tom'
age: 23
books: {
no1: 'abc', no2: 'def'}
(3)创建Author实体类,使用@ConfigurationProperties和@Component注解实现bean的注入。
package com.etc.ssm.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "author")
public class Author {
private int id;
private String name;
private int age;
private Map books;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Map getBooks() {
return books;
}
public void setBooks(Map books) {
this.books = books;
}
@Override
public String toString() {
return "Author{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", books=" + books +
'}';
}
}
(4)创建测试类,输出author对象。
package com.etc.ssm;
import com.etc.ssm.entity.Author;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AuthorApplicationTest {
@Autowired
Author author;
@Test
void contextLoads() {
System.out.println(author);
}
}
4、使用application.yml代替application.properties
(1)application.properties
#修改tomcat的端口
server.port=8080
#数据库连接配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bookdb?serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
#指定mybatis中配置的映射文件的地址
mybatis.mapper-locations=classpath:/mapper/*.xml
##日志配置
logging.level.com.etc.ssm.dao=DEBUG
logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n
##thymeleaf配置
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.content-type=text/html
(2)application.yml
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/bookdb?serverTimezone=Asia/Shanghai
username: root
password: root
thymeleaf:
cache: false
suffix: .html
prefix: classpath:/templates/
encoding: utf-8
mode: LEGACYHTML5
servlet:
content-type: text/html
mybatis:
mapper-locations: classpath:/mapper/*.xml
logging:
level:
com.etc.ssm.dao: debug
pattern:
console: '%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n'
file: '%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n'
三、PageHelper分页的使用
(1)在pom.xml文件中加入PageHelper的依赖。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
(2)在Service的实现类使用 PageHelper.startPage(page, limit);
,page为当前页,limit为每页的数量。
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public PageInfo<User> getUserByKeyWordsAndPage(Integer page, Integer limit, String keywords) {
if (page < 1) {
page = 1;
}
PageHelper.startPage(page, limit);
UserExample userExample = new UserExample();
userExample.createCriteria().andUsernameLike("%" + keywords + "%");
List<User> list = userMapper.selectByExample(userExample);
PageInfo<User> pd = new PageInfo<User>(list);
return pd;
}
}