Java微服务篇1——SpringBoot

Java微服务篇1——SpringBoot

1、什么是springboot

1.1、Spring出现的问题

Spring是Java企业版(Java Enterprise Edition,JEE,也称J2EE)的轻量级代替品。无需开发重量级的 Enterprise Java Bean(EJB),Spring为企业级Java开发提供了一种相对简单的方法,通过依赖注入和 面向切面编程,用简单的Java对象(Plain Old Java Object,POJO)实现了EJB的功能

  • 虽然Spring的组件代码是轻量级的,但它的配置却是重量级的。一开始,Spring用XML配置,而且是很 多XML配 置。Spring 2.5引入了基于注解的组件扫描,这消除了大量针对应用程序自身组件的显式XML 配置。Spring 3.0引入 了基于Java的配置,这是一种类型安全的可重构配置方式,可以代替XML

  • 所有这些配置都代表了开发时的损耗。因为在思考Spring特性配置和解决业务问题之间需要进行思维切 换,所以编写配置挤占了编写应用程序逻辑的时间。和所有框架一样,Spring实用,但与此同时它要求 的回报也不少

  • 除此之外,项目的依赖管理也是一件耗时耗力的事情。在环境搭建时,需要分析要导入哪些库的坐标, 而且还需要分析导入与之有依赖关系的其他库的坐标,一旦选错了依赖的版本,随之而来的不兼容问题 就会严重阻碍项目的开发进度

1.2、SpringBoot的诞生

SpringBoot对上述Spring的缺点进行的改善和优化,基于约定优于配置的思想,可以让开发人员不必在 配置与逻辑 业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而大大提高了开发的 效率,一定程度上缩短 了项目周期

  • 起步依赖:本质上是一个Maven项目对象模型(Project Object Model,POM),定义了对其他库的传递依 赖,这些东西加在一起即支持某项功能。 简单的说,起步依赖就是将具备某种功能的依赖坐标打包到一起,并提供一些默认的功能
  • 自动装配:指的是springboot,会自动将一些配置类的bean注册进ioc容器,我们可以需 要的地方使用@autowired或者@resource等注解来使用它。 “自动”的表现形式就是我们只需要引我们想用功能的包,相关的配置我们完全不用管,springboot会自 动注入这些配置bean,我们直接使用这些bean即可

2、SpringBoot核心理念

约定大于配置

Build Anything with Spring Boot:Spring Boot is the starting point forbuilding all Spring-based applications. Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring.

使用Spring Boot构建任何东西:Spring Boot是构建所有基于Spring的应用程序的起点。Spring Boot的设计目的是让您以最少的Spring前端配置尽快启动和运行

3、SpringBoot快速入门

3.1、创建项目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.2、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--
    所有的springBoot项目都会直接或者间接的继承spring-boot-starter-parent
    1.指定项目的编码格式为UTF-8
    2.指定JDK版本为1.8
    3.对项目依赖的版本进行管理,当前项目再引入其他常用的依赖时就需要再指定版本号,避免版本冲突的问题
    4.默认的资源过滤和插件管理
    -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.winkto</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!--可以将project打包为一个可以执行的jar-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.3、启动类

// SpringBoot的启动类通常放在二级包中,SpringBoot项目在做包扫描,会扫描启动类所在的包及其子包下的所有内容。

//标识当前类为SpringBoot项目的启动类
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

3.4、Controller

@RestController
public class SpringBootController {
    @RequestMapping("/hello")
    public String hello(){
        return "Hello, SpringBoot!";
    }
}

4、SpringBoot单元测试

// 标记为当前类为SpringBoot测试类,加载项目的ApplicationContext上下文环境
@SpringBootTest
class DemoApplicationTests {

    @Autowired
    SpringBootController springBootController;

    @Test
    void contextLoads() {
        System.out.println(springBootController.hello());
    }

}

5、热部署

在开发过程中,通常会对一段业务代码不断地修改测试,在修改之后往往需要重启服务,有些服务 需要加载很久才能启动成功,这种不必要的重复操作极大的降低了程序开发效率。为此,Spring Boot框 架专门提供了进行热部署的依赖启动器,用于进行项目热部署,而无需手动重启项目。

5.1、导入依赖

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

5.2、开启Idea的自动编译

在这里插入图片描述

5.3、开启Idea的在项目运行中自动编译

Ctrl+Shift+Alt+/打开Maintenance选项框,勾选compiler.automake.allow.when.app.running

在这里插入图片描述
然后自行测试即可

6、配置文件

配置文件能够对一些默认配置值进行修改,Spring Boot使用一个application.properties或者application.yaml(application.yml)的文件作为全局配置文件,该文件存放在**src/main/resource目录(常用)**或者类路径的/config

实体类

@Component
// @ConfigurationProperties注解用来快速、方便地将配置文件中的自定义属性值批量注入到某个Bean对象的多个对应属性中(@Value仅支持基础类型!)
// 保证配置文件中person.xx与当前Person类的属性名一致
// 保证当前Person中的属性都具有set方法
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private int age;
    private double money;
    private String[] hobbies;
    private List<String> books;
    private Set<String> lotteries;
    private Map<String,String> bankcards;
    private Pet pet;
}
public class Pet {
    private String name;
    private int age;
}

@ConfigurationProperties(prefix = “person”)爆红问题

虽然爆红,但是不影响运行,实在看着不爽,引入一个依赖解决一下

<!--处理@ConfigurationProperties(prefix = "person")爆红-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

6.1、properties配置文件

#tomcat的端口号
server.port=8099

#基础类型
person.name=zhangsan
person.age=20
person.money=123.5
#数组和集合(list,set)种赋值方式可以互换
person.hobbies=basketball,football,volleyball
person.books[0]=book1
person.books[1]=book2
person.books[2]=book3
person.lotteries[0]=book1
person.lotteries[1]=book2
person.lotteries[2]=book3
#map
person.bankcards.ICBC=123456789
person.bankcards.ABC=987654321
#对象
person.pet.name=huahua
person.pet.age=2

6.2、yaml配置文件

YAML文件格式是Spring Boot支持的一种JSON文件格式,相较于传统的Properties配置文件,YAML文 件以数据为核心,是一种更为直观且容易被电脑识别的数据序列化格式,application.yaml配置文件的工作原理和application.properties是一样的,yaml格式配置文件看起来更简洁一些

对空格要求极其严格

server:
  port: 8099
person:
  name: zhangsan
  age: 20
  money: 123.5
  hobbies: baskball,football,volleyball
  books:
    - book1
    - book2
    - book3
  lotteries: [lottery1,lottery2,lottery3]
  bankcards: {ICBC: 123456789,ABC: 987654321}
  pet:
    name: huahua
    age: 2

6.3、测试

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    Person person;

    @Test
    void contextLoads() {
        System.out.println(person.toString());
    }

}

6.4、配置文件优先级

spring-boot-starter-parent-2.5.3.pom中出现这个的配置文件加载顺序,那么文件的优先级yml<yaml<properties

<includes>
  <include>**/application*.yml</include>
  <include>**/application*.yaml</include>
  <include>**/application*.properties</include>
</includes>

6.5、自定义配置文件

有时候我们需要一些额外的配置文件,比如secretkey.properties,但是SpringBoot并不知道我们要加载这个配置文件,此时我们需要使用@PropertySource加载自定义配置文件(@PropertySource只对properties文件可以进行加载,对于yml或者yaml不能支持,需要自行实现)

@Component
@PropertySource("classpath:secretkey.properties")
@ConfigurationProperties(prefix = "secretkey")
public class SecretKey {
    private int num;
    private String secretkey;

    public SecretKey() {
    }

    public SecretKey(int num, String secretkey) {
        this.num = num;
        this.secretkey = secretkey;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getSecretkey() {
        return secretkey;
    }

    public void setSecretkey(String secretkey) {
        this.secretkey = secretkey;
    }

    @Override
    public String toString() {
        return "SecretKey{" +
                "num=" + num +
                ", secretkey='" + secretkey + '\'' +
                '}';
    }
}
secretkey.num=22
secretkey.secretkey=abcdefg
// 标记为当前类为SpringBoot测试类,加载项目的ApplicationContext上下文环境
@SpringBootTest
class DemoApplicationTests {

    @Autowired
    SecretKey secretKey;

    @Test
    void contextLoads() {
        System.out.println(secretKey.toString());
    }

}

6.6、自定义配置类(推荐使用)

在Spring Boot框架中,通常使用@Configuration注解定义一个配置类,Spring Boot会自动扫描和识别 配置类,从而替换传统Spring框架中的XML配置文件

// 标识该类是一个配置类
@Configuration
public class WinktoConfig {
    // 将返回值对象作为组件添加到Spring容器中,该组件id默认为方法名
    @Bean
    public ObjectMapper objectMapper(){
        return new ObjectMapper();
    }
}
@SpringBootTest
class DemoApplicationTests {

    @Autowired
    SecretKey secretKey;

    @Autowired
    ObjectMapper objectMapper;

    @Test
    void contextLoads() throws JsonProcessingException {
        System.out.println(objectMapper.writeValueAsString(secretKey));
    }

}

6.7、多配置文件

application.yaml可以放在以下位置

file:./config/
file:./
classpath:/config/
classpath:/

在这里插入图片描述

可自行设置端口号进行测试,上述给出的顺序就是优先级从高到低的顺序

6.8、多环境

application-prod.yaml

server:
  port: 8099

application-dev.yaml

server:
  port: 8080

application.yaml

spring:
  profiles:
    active: prod

在这里插入图片描述

上述三个文档也可以写在一个文档里

application.yaml

spring:
  profiles:
    active: prod
---
server:
  port: 8081
spring:
  profiles: dev
---
server:
  port: 8099
spring:
  profiles: prod

7、SpringBoot整合持久层

数据库准备

CREATE TABLE person(
	pid INT PRIMARY,
	pname VARCHAR(20),
	ppassword VARCHAR(20)
)

实体类

public class Person {
    private int pid;
    private String pname;
    private String ppassword;
}

7.1、JDBC

7.1.1、导入依赖
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>
7.1.2、application.yaml
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: blingbling123.
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
7.1.3、controller

这里我就不在分层,直接写在controller里

@RestController
public class SpringBootController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @RequestMapping("/select")
    public List<Map<String, Object>> select(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from person");
        return list;
    }
    @RequestMapping("/insert")
    public List<Map<String,Object>> insert(){
        jdbcTemplate.update("insert into person values (10,'小明','xiaoming')");
        List<Map<String, Object>> list = select();
        return list;
    }
    @RequestMapping("/update")
    public List<Map<String,Object>> update(){
        jdbcTemplate.update("update person set pname='小小明',ppassword='123456' where pid=10");
        List<Map<String, Object>> list = select();
        return list;
    }
    @RequestMapping("/delete")
    public List<Map<String,Object>> delList(){
        jdbcTemplate.update("delete from person where pid=10");
        List<Map<String, Object>> list = select();
        return list;
    }
}

7.2、Mybaits

7.2.1、导入依赖
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>
7.2.2、mybatis书写
7.2.2.1、注解方式

mapper

@Repository
public interface PersonMapper {
    @Select("select * from person")
    public List<Person> selectPerson();
}

修改启动类

//标识当前类为SpringBoot项目的启动类
@SpringBootApplication
//指定扫描的mapper路径
@MapperScan("cn.winkto.mapper")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
7.2.2.2、配置文件方式

mapper

@Repository
public interface PersonMapper {
    public List<Person> selectPerson();
}

映射文件

<?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="cn.winkto.mapper.PersonMapper">
    <select id="selectPerson" resultType="Person">
        select * from person
    </select>
</mapper>

application.yaml配置映射文件地址及别名

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: blingbling123.
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
mybatis:
  #配置MyBatis的xml配置文件路径
  mapper-locations: classpath:mapper/*.xml
  #配置XML映射文件中指定的实体类别名路径
  type-aliases-package: cn.winkto.bean

修改启动类

//标识当前类为SpringBoot项目的启动类
@SpringBootApplication
//指定扫描的mapper路径
@MapperScan("cn.winkto.mapper")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
7.2.3、测试
// 标记为当前类为SpringBoot测试类,加载项目的ApplicationContext上下文环境
@SpringBootTest
class DemoApplicationTests {

    @Autowired
    PersonMapper personMapper;

    @Test
    void contextLoads() throws JsonProcessingException {
        System.out.println(personMapper.selectPerson());
    }

}

7.3、Redis

7.3.1、导入依赖
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>
7.3.2、application.yaml

需要注意的是,springboot2.x中spring-boot-starter-data-redis使用的不再是jedis,而是lettuce,所以如果设置连接池,需要选择lettuce下的连接池

spring:
  redis:
    host: 132.232.82.49
7.3.3、测试
// 标记为当前类为SpringBoot测试类,加载项目的ApplicationContext上下文环境
@SpringBootTest
class DemoApplicationTests {

    @Autowired
    RedisTemplate redisTemplate;

    @Test
    void contextLoads() throws JsonProcessingException {
        // 操作字符串:redisTemplate.opsForValue()
        // 操作list集合:redisTemplate.opsForList()
        // 操作set集合:redisTemplate.opsForSet();
        // 操作hash:redisTemplate.opsForHash();
        // 操作zset集合:redisTemplate.opsForZSet();
        // 操作地图数据:redisTemplate.opsForGeo();
        // 操作HyperLogLog:redisTemplate.opsForHyperLogLog();
        // 除了公用,常用操作被提取出来了,其他的操作如同jedis
        redisTemplate.opsForValue().set("k1","v1");
        System.out.println(redisTemplate.opsForValue().get("k1"));
    }

}

8、SpringBoot视图层

前端模板引擎技术的出现,使前端开发人员无需关注后端业务的具体实现,只关注自己页面的呈现效果即可,并且解决了前端代码错综复杂的问题、实现了前后端分离开发

Spring Boot框架对很多常用的模板引擎技术(如:FreeMarker、Thymeleaf、Mustache等)提供了整合支持

8.1、静态资源目录

#webjars
classpath:/NETA-INF/resources/
#上传文件
classpath:/resources/
#图片等
classpath:/static/
#css、js等
classpath:/public/

注意优先级,从上到下从高到低

resources/templates相当于之前的WEB-INF目录,下面的页面只能通过controller进行访问,并且需要模板引擎

自定义页面图标:起名为favicon.icon,放入resources

8.2、Thymeleaf

8.2.1、Thymeleaf快速入门
th标签说明
th:utext取值,并按照html格式进行解析
th:text仅取值

Thymeleaf内置对象

#ctx:上下文对象,可以从中获取所有的thymeleaf内置对象
#arrays:数组操作的工具
#aggregates:操作数组或集合的工具
#bools:判断boolean类型的工具
#calendars:类似于#dates,但是是java.util.Calendar类的方法
#dates:日期格式化内置对象,具体方法可以参照java.util.Date
#numbers: 数字格式化;#strings:字符串格式化,具体方法可以参照java.lang.String,如startsWith、contains等;#objects:参照java.lang.Object
#lists:列表操作的工具,参照java.util.List
#sets:Set操作工具,参照java.util.Set;#maps:Map操作工具,参照java.util.Map
#messages:操作消息的工具

导入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</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-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>

controller

@Controller
public class SpringBootController {
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("text","<h1>Hello, Thymeleaf!</h1>");
        return "hello";
    }
}

页面

# thymeleaf约束
xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:utext="${text}"></p>
<p th:text="${text}"></p>
</body>
</html>
8.2.2、th:href和th:src
th标签说明
th:href用于html页面link标签引入css(需使用@{}表达式)
th:src用于html页面script标签引入js(需使用@{}表达式)

目录结构

在这里插入图片描述

controller

@Controller
public class SpringBootController {
    @RequestMapping("/path")
    public String path(){
        return "path";
    }
}

css

.card{
    width: 50px;
    height: 50px;
    background-color: skyblue;
}

js

window.onload=function () {
    let cards = document.getElementsByClassName("card")
    for (let i = 0; i < cards.length; i++) {
        cards[i].onclick=f;
    }
    function f() {
        alert("我被点击了!")
    }
}

页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--对于th:href和th:src而言,静态资源目录可以省略-->
    <link rel="stylesheet" th:href="@{/card.css}">
</head>
<body>
    <div class="card">1</div>
    <div class="card">2</div>
</body>
<!--对于th:href和th:src而言,静态资源目录可以省略-->
<script th:src="@{/tap.js}"></script>
</html>
8.2.3、th:if和th:unless
th标签说明
th:if如果为真,则显示
th:unless如果为假,则显示

controller

@Controller
public class SpringBootController {
    @RequestMapping("/condition")
    public String condition(Model model){
        model.addAttribute("flagif",true);
        model.addAttribute("flagunless",false);
        return "condition";
    }
}

页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:if="${flagif}">th:if</p>
<p th:unless="${flagunless}">th:unless</p>
</body>
</html>
8.2.4、th:each
th标签说明
th:eachfor循环,例如:

controller

@Controller
public class SpringBootController {
    @RequestMapping("/each")
    public String each(Model model){
        model.addAttribute("list", Arrays.asList("book","code","music","dance"));
        return "each";
    }
}

页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <ul>
        <li th:each="item:${list}" th:text="${item}"></li>
    </ul>
</div>
</body>
</html>
8.2.5、th:switch和th:case
th标签说明
th:switch如果为真,则显示
th:case如果为假,则显示

controller

@Controller
public class SpringBootController {
    @RequestMapping("/switch")
    public String switch1(Model model){
        model.addAttribute("gender", 1);
        return "switch";
    }
}

页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>性别</p>
<div th:switch="${gender}">
    <p th:case=1></p>
    <p th:case=0></p>
    <p th:case=*>未知</p>
</div>
</body>
</html>
8.2.6、th:insert和th:replace
th标签说明
th:insert在原有标签内插入指定内容,例如:th:insert="~{public::header}"
th:replace用指定内容替换原有标签,例如:th:replace="~{public::header}"

controller

@Controller
public class SpringBootController {
    @RequestMapping("/contain")
    public String contain(Model model){
        return "contain";
    }
}

页面(public.html)

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<nav th:fragment="header">
    <a href="#">首页</a>
    <a href="#">分类</a>
</nav>
</body>
</html>

页面(contain.html)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            background-color: skyblue;
        }
    </style>
</head>
<body>
<div th:insert="~{public::header}">
</div>
<div th:replace="~{public::header}">
</div>
</body>
</html>

html页面源码

在这里插入图片描述

8.2.7、th:class

controller

@Controller
public class SpringBootController {
    @RequestMapping("/class")
    public String classes(Model model){
        model.addAttribute("classes", "red");
        return "class";
    }
}

页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .red{
            background-color: red;
        }
        .blue{
            background-color: blue;
        }
    </style>
</head>
<body>
<div th:class="${classes=='red'}?'red':'blue'">
    动态class
</div>
</body>
</html>

8.3、错误处理

在templates下建error文件夹,然后在下面放xxx.html即可,例如:404.html,500.html

8.4、页面国际化

application.yaml

spring:
  messages:
    basename: i18n.login

国际化文件

在这里插入图片描述

# login.properties
login.btn=登录
login.username=用户名
login.password=密码
login.passwordPlaceholder=请输入密码
login.usernamePlaceholder=请输入用户名
# login_zh_CN.properties
login.btn=登录
login.username=用户名
login.password=密码
login.passwordPlaceholder=请输入密码
login.usernamePlaceholder=请输入用户名
# login_en_US.properties
login.btn=login
login.username=username
login.password=password
login.passwordPlaceholder=Please input your password
login.usernamePlaceholder=Please enter your user name

覆盖默认WebMvcConfigurer中的LocaleResolver

public class WinktoLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        // 接收语言的参数 - 传进来的就是形如'zh_CN'这样的参数
        String lang = httpServletRequest.getParameter("lang");
        System.out.println(lang);
        // 使用默认的语言 - 在文中就是login.properties文件里配置的
        Locale locale = Locale.getDefault();
        // 判断接收的参数是否为空,不为空就设置为该语言
        if(!StringUtils.isEmpty(lang)){
            // 将参数分隔 - 假设传进来的是'zh_CN'
            String[] s = lang.split("_");
            // 语言编码:zh   地区编码:CN
            locale = new Locale(s[0],s[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}
@Configuration
public class WinktoWebMvcConfig implements WebMvcConfigurer {
    @Bean
    public LocaleResolver localeResolver(){
        return new WinktoLocaleResolver();
    }
}

页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form>
    <label for="username" th:text="#{login.username}">username</label>
    <input type="text" id="username" name="username" th:placeholder="#{login.usernamePlaceholder}">
    <label for="password" th:text="#{login.password}">password</label>
    <input type="password" id="password" name="password" th:placeholder="#{login.passwordPlaceholder}">
    <input type="submit" th:value="#{login.btn}">
    <br>
    <a th:href="@{/login(lang='zh_CN')}">中文</a>
    <a th:href="@{/login(lang='en_US')}">英文</a>
</form>
</body>
</html>

9、安全与授权

Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,可以实现强大的Web安全控制

  • 用户认证:系统认为用户是否能登录
  • 用户授权:通俗点讲就是系统判断用户是否有权限去做某些事情

9.1、快速入门

导入依赖

<dependencies>
    <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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

页面(index.html)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/v/1}">v1</a>
<a th:href="@{/v/2}">v2</a>
<a th:href="@{/v/3}">v3</a>
</body>
</html>

页面(v1.html,v2.html,v3.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
v1
</body>
</html>

页面(403.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>权限不足哦!</h1>
</body>
</html>

访问http://localhost:8080/发现跟我们预料的不一样

在这里插入图片描述

需要输入用户名密码,其实这是因为引入spring-boot-starter-security的原因,默认有用户名为user,密码在控制台已经打印出来了

在这里插入图片描述

9.2、认证(账号密码来源)

9.2.1、默认

上述就是默认的账号密码

9.2.2、application.properties(application.yaml)
spring.security.user.name=della
spring.security.user.password=della
9.2.3、配置类

需要覆盖WebSecurityConfigurerAdapter中的configure(AuthenticationManagerBuilder auth)方法,在内存中处理账号密码

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("della").password(new BCryptPasswordEncoder().encode("123456")).roles("v2","v3")
                .and()
                .withUser("author").password(new BCryptPasswordEncoder().encode("123456")).roles("v1");
    }
}
9.2.4、自定义认证接口

实现UserDetailsService接口,定义认证逻辑

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (s==null){
            return null;
        }
        System.out.println("自定义处理逻辑");
        // 假装自己查了数据库,密码为123456
        return new User(s,passwordEncoder.encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("v2,v3"));
    }
}

覆盖默认认证逻辑

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}

9.3、自定义登录页(走)

目录结构

在这里插入图片描述

SecurityConfig

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 放行静态资源下的文件,如果不放行,会卡死在登录页!!!(AuthenticationFailureHandler和AuthenticationSuccessHandler都不会触发,甚至是自定义的UserDetailsService都不会触发)
                .antMatchers("/static/**").permitAll()
                // 所有的请求必须登录后才能访问,除了上面定义的(注意anyRequest必须是页面拦截的最后一个)
                .anyRequest().authenticated()
                .and()
                // 自定义登录逻辑,并放行登陆相关页面
                .formLogin().loginPage("/login.html")
                // 登陆处理逻辑接口(可以自定义为其他接口,这样无需实现UserDetailsService)
                .loginProcessingUrl("/login")
                // 成功跳转页面
                .successForwardUrl("/")
                // 失败跳转页面
                .failureForwardUrl("/login.html")
                // 自定义接受参数
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
                .and()
                // 关闭csrf防护,不关闭也会导致卡死在登录页
                .csrf().disable();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}

页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login" method="post">
    <label for="username">username</label>
    <input type="text" id="username" name="username" placeholder="usernamePlaceholder">
    <label for="password">password</label>
    <input type="password" id="password" name="password" placeholder="passwordPlaceholder">
    <input type="submit" value="login">
</form>
</body>
</html>

9.4、授权

9.4.1、antMatchers
  • ?:匹配一个字符
  • *:匹配0个或多个字符
  • **:匹配一个或多个目录
9.4.2、hasAuthority

与UserDetailsServiceImpl中的AuthorityUtils对应,并且严格区分大小写

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 放行静态资源下的文件,如果不放行,会卡死在登录页!!!(AuthenticationFailureHandler和AuthenticationSuccessHandler都不会触发,甚至是自定义的UserDetailsService都不会触发)
                .antMatchers("/static/**").permitAll()
                // 角色判断
                .antMatchers("/v/1").hasAuthority("v1")
                .antMatchers("/v/2").hasAuthority("v2")
                .antMatchers("/v/3").hasAuthority("v3")
                // 所有的请求必须登录后才能访问,除了上面定义的(注意anyRequest必须是页面拦截的最后一个)
                .anyRequest().authenticated()
                .and()
                // 自定义登录逻辑,并放行登陆相关页面
                .formLogin().loginPage("/login.html")
                // 登陆处理逻辑接口
                .loginProcessingUrl("/login")
                // 成功跳转页面
                .successForwardUrl("/")
                // 失败跳转页面
                .failureForwardUrl("/login.html")
                // 自定义接受参数
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
                .and()
                // 关闭csrf防护,不关闭也会导致卡死在登录页
                .csrf().disable();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}
9.4.3、hasRole

角色必须以ROLE_开头(大小写也必须一致)

UserDetailsServiceImpl

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println(s);
        if (s==null){
            return null;
        }
        System.out.println("自定义处理逻辑");
        // 假装自己查了数据库,密码为123456
        return new User(s,passwordEncoder.encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_v1,v2,v3"));
    }
}

SecurityConfig

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 放行静态资源下的文件,如果不放行,会卡死在登录页!!!(AuthenticationFailureHandler和AuthenticationSuccessHandler都不会触发,甚至是自定义的UserDetailsService都不会触发)
                .antMatchers("/static/**").permitAll()
                // 角色判断
                .antMatchers("/v/1").hasRole("v1")
                .antMatchers("/v/2").hasAuthority("v2")
                .antMatchers("/v/3").hasAuthority("v3")
                // 所有的请求必须登录后才能访问,除了上面定义的(注意anyRequest必须是页面拦截的最后一个)
                .anyRequest().authenticated()
                .and()
                // 自定义登录逻辑,并放行登陆相关页面
                .formLogin().loginPage("/login.html")
                // 登陆处理逻辑接口
                .loginProcessingUrl("/login")
                // 成功跳转页面
                .successForwardUrl("/")
                // 失败跳转页面
                .failureForwardUrl("/login.html")
                // 自定义接受参数
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
                .and()
                // 关闭csrf防护,不关闭也会导致卡死在登录页
                .csrf().disable();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}

9.5、基于注解的访问控制

注解功能默认关闭,需要手动开启

9.5.1、@Secured(用于角色)

取消代码权限控制

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 放行静态资源下的文件,如果不放行,会卡死在登录页!!!(AuthenticationFailureHandler和AuthenticationSuccessHandler都不会触发,甚至是自定义的UserDetailsService都不会触发)
                .antMatchers("/static/**").permitAll()
                // 角色判断
                //.antMatchers("/v/1").hasRole("v1")
                //.antMatchers("/v/2").hasAuthority("v2")
                //.antMatchers("/v/3").hasAuthority("v3")
                // 所有的请求必须登录后才能访问,除了上面定义的(注意anyRequest必须是页面拦截的最后一个)
                .anyRequest().authenticated()
                .and()
                // 自定义登录逻辑,并放行登陆相关页面
                .formLogin().loginPage("/login.html")
                // 登陆处理逻辑接口
                .loginProcessingUrl("/login")
                // 成功跳转页面
                .successForwardUrl("/")
                // 失败跳转页面
                .failureForwardUrl("/login.html")
                // 自定义接受参数
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
                .and()
                // 关闭csrf防护,不关闭也会导致卡死在登录页
                .csrf().disable();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}

修改启动类

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

接口上书写注解

@Controller
public class WinktoController {
    @RequestMapping("/")
    public String index(){
        return "index";
    }
    @RequestMapping("/v/{id}")
    @Secured("ROLE_v1")
    public String v(@PathVariable int id){
        System.out.println(id);
        return "v"+id;
    }
}
9.5.2、@PreAuthorize和@PostAuthorize

这两个注解都是使用access表达式

在这里插入图片描述

修改启动类

@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

接口上书写注解

@Controller
public class WinktoController {
    @RequestMapping("/")
    public String index(){
        return "index";
    }
    @RequestMapping("/v/{id}")
    // 方法执行前判断
    @PreAuthorize("hasAuthority('v2')")
    //方法执行后判断
    // @PostAuthorize()
    public String v(@PathVariable int id){
        System.out.println(id);
        return "v"+id;
    }
}

9.6、退出登录

SecurityConfig

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 放行静态资源下的文件,如果不放行,会卡死在登录页!!!(AuthenticationFailureHandler和AuthenticationSuccessHandler都不会触发,甚至是自定义的UserDetailsService都不会触发)
                .antMatchers("/static/**").permitAll()
                // 角色判断
                //.antMatchers("/v/1").hasRole("v1")
                //.antMatchers("/v/2").hasAuthority("v2")
                //.antMatchers("/v/3").hasAuthority("v3")
                // 所有的请求必须登录后才能访问,除了上面定义的(注意anyRequest必须是页面拦截的最后一个)
                .anyRequest().authenticated()
                .and()
                // 自定义登录逻辑,并放行登陆相关页面
                .formLogin().loginPage("/login.html")
                // 登陆处理逻辑接口
                .loginProcessingUrl("/login")
                // 成功跳转页面
                .successForwardUrl("/")
                // 失败跳转页面
                .failureForwardUrl("/login.html")
                // 自定义接受参数
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .and()
                // 关闭csrf防护,不关闭也会导致卡死在登录页
                .csrf().disable();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}

页面(index.html)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/v/1}">v1</a>
<a th:href="@{/v/2}">v2</a>
<a th:href="@{/v/3}">v3</a>
<br>
<a href="/logout">退出登录</a>
</body>
</html>

9.7、Thymeleaf整合Spring Security

导入依赖

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

引入约束

xmlns:sec="http://www.thymeleaf.org/extras/spring-security"(注意是这个)
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"(这个跟最新版本不匹配)

页面(index.html)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/v/1}">v1</a>
<a th:href="@{/v/2}">v2</a>
<a th:href="@{/v/3}">v3</a>
<br>
账号 <p sec:authentication="name"></p>
密码 <p sec:authentication="principal.username"></p>
凭证 <p sec:authentication="credentials"></p>
权限 <p sec:authentication="authorities"></p>
地址<p sec:authentication="details.remoteAddress"></p>
session<p sec:authentication="details.sessionId"></p>
<br>
v1 <p sec:authorize="hasRole('v1')"></p>
v2 <p sec:authorize="hasAuthority('v2')"></p>
v3 <p sec:authorize="hasAuthority('v3')"></p>
</body>
</html>

10、任务

10.1、异步任务

导入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

任务

@Component
public class WinktoTask {
    public void sync() throws InterruptedException {
        Thread.sleep(5000);
        System.out.println("邮件发送成功!");
    }
    // 标记为异步任务
    @Async
    public void async() throws InterruptedException {
        Thread.sleep(5000);
        System.out.println("邮件发送成功!");
    }
}

接口

@RestController
public class WinktoController {
    @Autowired
    WinktoTask winktoTask;
    @RequestMapping("/sync")
    public String sync() throws InterruptedException {
        winktoTask.sync();
        return "ok";
    }
    @RequestMapping("/async")
    public String async() throws InterruptedException {
        winktoTask.async();
        return "ok";
    }
}

启动类

@SpringBootApplication
// 开启异步任务功能
@EnableAsync
public class TaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(TaskApplication.class, args);
    }

}

10.2、定时任务

10.2.1、cron表达式
  • Seconds Minutes Hours DayofMonth Month DayofWeek Year
  • Seconds Minutes Hours DayofMonth Month DayofWeek
字段允许值允许的特殊字符
秒(Seconds)0~59的整数, - * / 四个字符
分(Minutes0~59的整数, - * / 四个字符
小时(Hours0~23的整数, - * / 四个字符
日期(DayofMonth1~31的整数(但是你需要考虑你月的天数),- * ? / L W C 八个字符
月份(Month1~12的整数或者 JAN-DEC, - * / 四个字符
星期(DayofWeek1~7的整数或者 SUN-SAT (1=SUN), - * ? / L C # 八个字符
年(可选,留空)(Year1970~2099, - * / 四个字符
  • *表示匹配该域的任意值。假如在Minutes域使用, 即表示每分钟都会触发事件。
  • ?:只能用在DayofMonth和DayofWeek两个域。它也匹配域的任意值,但实际不会。因为DayofMonth和DayofWeek会相互影响。例如想在每月的20日触发调度,不管20日到底是星期几,则只能使用如下写法: 13 13 15 20 * ?, 其中最后一位只能用?,而不能使用*,如果使用*表示不管星期几都会触发,实际上并不是这样。
  • -:表示范围。例如在Minutes域使用5-20,表示从5分到20分钟每分钟触发一次
  • /:表示起始时间开始触发,然后每隔固定时间触发一次。例如在Minutes域使用5/20,则意味着5分钟触发一次,而25,45等分别触发一次.
  • ,:表示列出枚举值。例如:在Minutes域使用5,20,则意味着在5和20分每分钟触发一次。
  • L:表示最后,只能出现在DayofWeek和DayofMonth域。如果在DayofWeek域使用5L,意味着在最后的一个星期四触发。
  • W:表示有效工作日(周一到周五),只能出现在DayofMonth域,系统将在离指定日期的最近的有效工作日触发事件。例如:在 DayofMonth使用5W,如果5日是星期六,则将在最近的工作日:星期五,即4日触发。如果5日是星期天,则在6日(周一)触发;如果5日在星期一到星期五中的一天,则就在5日触发。另外一点,W的最近寻找不会跨过月份 。
  • LW:这两个字符可以连用,表示在某个月最后一个工作日,即最后一个星期五。
  • #:用于确定每个月第几个星期几,只能出现在DayofMonth域。例如在4#2,表示某月的第二个星期三。

实例

0 0 2 1 * ? *   表示在每月的1日的凌晨2点调整任务

0 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业

0 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作

0 0 10,14,16 * * ?   每天上午10点,下午2点,4点 

0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时 

0 0 12 ? * WED    表示每个星期三中午12点 

0 0 12 * * ?   每天中午12点触发 

0 15 10 ? * *    每天上午10:15触发 

0 15 10 * * ?     每天上午10:15触发 

0 15 10 * * ? *    每天上午10:15触发 

0 15 10 * * ? 2005    2005年的每天上午10:15触发 

0 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发 

0 0/5 14 * * ?    在每天下午2点到下午2:55期间的每5分钟触发 

0 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 

0 0-5 14 * * ?    在每天下午2点到下午2:05期间的每1分钟触发 

0 10,44 14 ? 3 WED    每年三月的星期三的下午2:10和2:44触发 

0 15 10 ? * MON-FRI    周一至周五的上午10:15触发 

0 15 10 15 * ?    每月15日上午10:15触发 

0 15 10 L * ?    每月最后一日的上午10:15触发 

0 15 10 ? * 6L    每月的最后一个星期五上午10:15触发 

0 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发 

0 15 10 ? * 6#3   每月的第三个星期五上午10:15触发
10.2.2、案例

导入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

任务

@Component
public class WinktoTask {
	//每分钟的0秒执行
    //秒 时 分 日 月 周
    @Scheduled(cron = "0 * * * * ?")
    public void helloScheduled(){
        System.out.println(new Date()+"我执行啦!");
    }
}

启动器

@SpringBootApplication
// 开启定时任务功能
@EnableScheduling
public class TaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(TaskApplication.class, args);
    }

}

在这里插入图片描述

11、邮件

开启qq邮箱pop3/mtp服务

在这里插入图片描述

11.1、依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

11.2、application.yaml

spring:
  mail:
    username: 2750955630@qq.com
    # 填写上你自己的密钥
    password: zpcp********dfbg
    host: smtp.qq.com
    properties:
      mail:
        smtp:
          ssl:
            enable: true
    port: 465
    default-encoding: UTF-8

11.3、任务

@Component
public class WinktoTask {
    @Autowired
    JavaMailSenderImpl javaMailSender;
    @Async
    public void simpleMail() {
        //简单邮件
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("2750955630@qq.com");
        simpleMailMessage.setTo("winkto@126.com");
        simpleMailMessage.setSubject("通知");
        simpleMailMessage.setText("很高兴你能加入我们!");

        javaMailSender.send(simpleMailMessage);
    }
    @Async
    public void mimeMessage() throws MessagingException, URISyntaxException {
        //复杂邮件
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        mimeMessageHelper.setFrom("2750955630@qq.com");
        mimeMessageHelper.setTo("winkto@126.com");
        mimeMessageHelper.setSubject("我是兰蔻");
        mimeMessageHelper.setText("欢迎你加入我们!");
        ClassLoader classLoader=ClassLoader.getSystemClassLoader();
        // 目录以resources为基目录
        URL resource = classLoader.getResource("1.txt");
        //断言
        assert resource != null;
        //添加附件
        mimeMessageHelper.addAttachment("1.txt", new File(resource.getFile()));
        javaMailSender.send(mimeMessage);
    }
}

11.4、controller

@RestController
public class WinktoController {
    @Autowired
    WinktoTask winktoTask;
    @RequestMapping("simpleMail")
    public String simpleMail(){
        winktoTask.simpleMail();
        return "邮件发送成功!";
    }
    @RequestMapping("mimeMessage")
    public String mimeMessage() throws MessagingException, URISyntaxException {
        winktoTask.mimeMessage();
        return "邮件发送成功!";
    }
}

11.5、启动类

@SpringBootApplication
@EnableAsync
public class TaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(TaskApplication.class, args);
    }

}

11.5、效果

简单邮件

在这里插入图片描述

带附件的邮件

在这里插入图片描述

12、Swagger

12.1、依赖

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

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.4.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
</dependencies>

12.2、Swagger配置类

@Configuration
public class SwaggerConfig {
    Boolean swaggerEnabled=true;
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo())
                // 是否开启
                .enable(swaggerEnabled).select()
                // 扫描的路径包
                .apis(RequestHandlerSelectors.basePackage("cn.winkto.vueserver"))
                // 指定路径处理PathSelectors.any()代表所有的路径
                .paths(PathSelectors.any()).build().pathMapping("/");
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Vue3 axios封装测试")
                .description("springboot | swagger")
                // 作者信息
                .contact(new Contact("wenley", "www.baidu.com", "wenley.yu@qq.com"))
                .version("1.0.0")
                .build();
    }
}

12.3、controller

@RestController
@CrossOrigin
@Api(tags = "HelloController!")
public class HelloController {

    @ApiOperation("get测试")
    @GetMapping("/get")
    public String get(@ApiParam("get参数") @RequestParam String str, @ApiParam("get参数1") @RequestParam String str1) {
        return "hello " + str + ' ' + str1;
    }

    @ApiOperation("post测试")
    @PostMapping("/post")
    public String post(@ApiParam("get参数") @RequestBody String str) {
        return "hello " + str;
    }

    @ApiOperation("file测试")
    @PostMapping("/file")
    public String file(@ApiParam("文件") @RequestBody String str) {
        return "hello" + str;
    }
}

12.4、效果

在这里插入图片描述

12.5、注意事项

springboot超过2.6.0,需在application.properties添加

spring.mvc.pathmatch.matching-strategy= ANT_PATH_MATCHER

13、文件上传下载

13.1、依赖

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

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

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
</dependencies>

13.2、配置

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=30MB

13.3、上传

@PostMapping("/file")
public String file(@RequestParam(value = "file", required = true) MultipartFile file) throws IOException {
    String upload = "D:\\upload";
    File file1 = new File(upload);
    if (!file1.exists()) {
        file1.mkdir();
    }
    String path = upload + File.separator + file.getOriginalFilename();

    File destination = new File(path);
    if (!destination.getParentFile().exists()) {
        //使用commons-io的工具类
        FileUtils.forceMkdirParent(destination);
    }
    file.transferTo(destination);
    return "success:" + path;
}

13.4、前端

<form action="http://localhost:8099/file" method="post" enctype="multipart/form-data">
  <input type="file" name="file"/>
  <input type="submit" value="上传"/>
</form>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
【2021年,将Spring全家桶的课程进行Review,确保不再有课程的顺序错乱,从而导致学员看不懂。进入2022年,将Spring的课程进行整理,整理为案例精讲的系列课程,并开始加入高阶Spring Security等内容,一步步手把手教你从零开始学会应用Spring,课件将逐步进行上传,敬请期待!】 本课程是Spring全家桶系列课程的第三部分Spring Boot,Spring案例精讲课程以真实场景、项目实战为导向,循序渐进,深入浅出的讲解Java网络编程,助力您在技术工作中更进一步。 本课程聚焦Spring Boot核心知识点:整合Web(如:JSP、Thymeleaf、freemarker等的整合)的开发、全局异常处理、配置文件的配置访问、多环境的配置文件设置、日志Logback及slf4j的使用、国际化设置及使用, 并在最后以一个贯穿前后台的Spring Boot整合Mybatis的案例为终奖,使大家快速掌握Spring的核心知识,快速上手,为面试、工作都做好充足的准备。 由于本课程聚焦于案例,即直接上手操作,对于Spring的原理等不会做过多介绍,希望了解原理等内容的需要通过其他视频或者书籍去了解,建议按照该案例课程一步步做下来,之后再去进一步回顾原理,这样能够促进大家对原理有更好的理解。 【通过Spring全家桶,我们保证你能收获到以下几点】 1、掌握Spring全家桶主要部分的开发、实现2、可以使用Spring MVC、Spring Boot、Spring Cloud及Spring Data进行大部分的Spring开发3、初步了解使用微服务、了解使用Spring进行微服务的设计实现4、奠定扎实的Spring技术,具备了一定的独立开发的能力  【实力讲师】 毕业于清华大学软件学院软件工程专业,曾在Accenture、IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,一直致力于架构、设计、开发及管理工作,在电商、零售、制造业等有丰富的项目实施经验  【本课程适用人群】如果你是一定不要错过!  适合于有JavaEE基础的,如:JSP、JSTL、Java基础等的学习者没有基础的学习者跟着课程可以学习,但是需要补充相关基础知识后,才能很好的参与到相关的工作中。 【Spring全家桶课程共包含如下几门】 

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

眼眸流转

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值