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实用,但与此同时它要求 的回报也不少
除此之外,项目的依赖管理也是一件耗时耗力的事情。在环境搭建时,需要分析要导入哪些库的坐标, 而且还需要分析导入与之有依赖关系的其他库的坐标,一旦选错了依赖的版本,随之而来的不兼容问题 就会严重阻碍项目的开发进度
SpringBoot对上述Spring的缺点进行的改善和优化,基于约定优于配置的思想,可以让开发人员不必在 配置与逻辑 业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而大大提高了开发的 效率,一定程度上缩短 了项目周期
约定大于配置
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前端配置尽快启动和运行
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.5.3version>
<relativePath/>
parent>
<groupId>cn.winktogroupId>
<artifactId>demoartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>demoname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
// SpringBoot的启动类通常放在二级包中,SpringBoot项目在做包扫描,会扫描启动类所在的包及其子包下的所有内容。
//标识当前类为SpringBoot项目的启动类
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
public class SpringBootController {
@RequestMapping("/hello")
public String hello(){
return "Hello, SpringBoot!";
}
}
// 标记为当前类为SpringBoot测试类,加载项目的ApplicationContext上下文环境
@SpringBootTest
class DemoApplicationTests {
@Autowired
SpringBootController springBootController;
@Test
void contextLoads() {
System.out.println(springBootController.hello());
}
}
在开发过程中,通常会对一段业务代码不断地修改测试,在修改之后往往需要重启服务,有些服务 需要加载很久才能启动成功,这种不必要的重复操作极大的降低了程序开发效率。为此,Spring Boot框 架专门提供了进行热部署的依赖启动器,用于进行项目热部署,而无需手动重启项目。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
dependency>
Ctrl+Shift+Alt+/打开Maintenance选项框,勾选compiler.automake.allow.when.app.running
配置文件能够对一些默认配置值进行修改,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”)爆红问题
虽然爆红,但是不影响运行,实在看着不爽,引入一个依赖解决一下
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
#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
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
@SpringBootTest
class DemoApplicationTests {
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person.toString());
}
}
spring-boot-starter-parent-2.5.3.pom中出现这个的配置文件加载顺序,那么文件的优先级yml 有时候我们需要一些额外的配置文件,比如secretkey.properties,但是SpringBoot并不知道我们要加载这个配置文件,此时我们需要使用@PropertySource加载自定义配置文件(@PropertySource只对properties文件可以进行加载,对于yml或者yaml不能支持,需要自行实现) 在Spring Boot框架中,通常使用@Configuration注解定义一个配置类,Spring Boot会自动扫描和识别 配置类,从而替换传统Spring框架中的XML配置文件 application.yaml可以放在以下位置 可自行设置端口号进行测试,上述给出的顺序就是优先级从高到低的顺序 application-prod.yaml application-dev.yaml application.yaml 上述三个文档也可以写在一个文档里 application.yaml 数据库准备 实体类 这里我就不在分层,直接写在controller里 mapper 修改启动类 mapper 映射文件 application.yaml配置映射文件地址及别名 修改启动类 需要注意的是,springboot2.x中spring-boot-starter-data-redis使用的不再是jedis,而是lettuce,所以如果设置连接池,需要选择lettuce下的连接池 前端模板引擎技术的出现,使前端开发人员无需关注后端业务的具体实现,只关注自己页面的呈现效果即可,并且解决了前端代码错综复杂的问题、实现了前后端分离开发 Spring Boot框架对很多常用的模板引擎技术(如:FreeMarker、Thymeleaf、Mustache等)提供了整合支持 注意优先级,从上到下从高到低 resources/templates相当于之前的WEB-INF目录,下面的页面只能通过controller进行访问,并且需要模板引擎 自定义页面图标:起名为favicon.icon,放入resources Thymeleaf内置对象 导入依赖 controller 页面 目录结构 controller css js 页面 controller 页面 controller 页面 controller 页面 controller 页面(public.html) 页面(contain.html) html页面源码 controller 页面 在templates下建error文件夹,然后在下面放xxx.html即可,例如:404.html,500.html application.yaml 国际化文件 覆盖默认WebMvcConfigurer中的LocaleResolver 页面 Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,可以实现强大的Web安全控制 导入依赖 页面(index.html) 页面(v1.html,v2.html,v3.html) 页面(403.html) 访问http://localhost:8080/发现跟我们预料的不一样 需要输入用户名密码,其实这是因为引入spring-boot-starter-security的原因,默认有用户名为user,密码在控制台已经打印出来了 上述就是默认的账号密码 需要覆盖WebSecurityConfigurerAdapter中的configure(AuthenticationManagerBuilder auth)方法,在内存中处理账号密码 实现UserDetailsService接口,定义认证逻辑 覆盖默认认证逻辑 目录结构 SecurityConfig 页面 与UserDetailsServiceImpl中的AuthorityUtils对应,并且严格区分大小写 角色必须以ROLE_开头(大小写也必须一致) UserDetailsServiceImpl SecurityConfig 注解功能默认关闭,需要手动开启 取消代码权限控制 修改启动类 接口上书写注解 这两个注解都是使用access表达式 修改启动类 接口上书写注解 SecurityConfig 页面(index.html) 导入依赖 引入约束 页面(index.html) 导入依赖 任务 接口 启动类 实例 导入依赖 任务 启动器 开启qq邮箱pop3/mtp服务 简单邮件 带附件的邮件 springboot超过2.6.0,需在application.properties添加<includes>
<include>**/application*.ymlinclude>
<include>**/application*.yamlinclude>
<include>**/application*.propertiesinclude>
includes>
6.5、自定义配置文件
@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、自定义配置类(推荐使用)
// 标识该类是一个配置类
@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、多配置文件
file:./config/
file:./
classpath:/config/
classpath:/
6.8、多环境
server:
port: 8099
server:
port: 8080
spring:
profiles:
active: prod
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.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
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
@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.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.2.0version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
dependency>
dependencies>
7.2.2、mybatis书写
7.2.2.1、注解方式
@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、配置文件方式
@Repository
public interface PersonMapper {
public List<Person> selectPerson();
}
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>
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.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
dependency>
dependencies>
7.3.2、application.yaml
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视图层
8.1、静态资源目录
#webjars
classpath:/NETA-INF/resources/
#上传文件
classpath:/resources/
#图片等
classpath:/static/
#css、js等
classpath:/public/
8.2、Thymeleaf
8.2.1、Thymeleaf快速入门
th标签
说明
th:utext
取值,并按照html格式进行解析
th:text
仅取值
#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:操作消息的工具
@Controller
public class SpringBootController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("text","
Hello, Thymeleaf!
");
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>Titletitle>
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
public class SpringBootController {
@RequestMapping("/path")
public String path(){
return "path";
}
}
.card{
width: 50px;
height: 50px;
background-color: skyblue;
}
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>Titletitle>
<link rel="stylesheet" th:href="@{/card.css}">
head>
<body>
<div class="card">1div>
<div class="card">2div>
body>
<script th:src="@{/tap.js}">script>
html>
8.2.3、th:if和th:unless
th标签
说明
th:if
如果为真,则显示
th:unless
如果为假,则显示
@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>Titletitle>
head>
<body>
<p th:if="${flagif}">th:ifp>
<p th:unless="${flagunless}">th:unlessp>
body>
html>
8.2.4、th:each
th标签
说明
th:each
for循环,例如:
@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>Titletitle>
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
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>Titletitle>
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
public class SpringBootController {
@RequestMapping("/contain")
public String contain(Model model){
return "contain";
}
}
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>Documenttitle>
head>
<body>
<nav th:fragment="header">
<a href="#">首页a>
<a href="#">分类a>
nav>
body>
html>
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<style>
div{
background-color: skyblue;
}
style>
head>
<body>
<div th:insert="~{public::header}">
div>
<div th:replace="~{public::header}">
div>
body>
html>
8.2.7、th:class
@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>Titletitle>
<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、错误处理
8.4、页面国际化
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
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>Titletitle>
head>
<body>
<form>
<label for="username" th:text="#{login.username}">usernamelabel>
<input type="text" id="username" name="username" th:placeholder="#{login.usernamePlaceholder}">
<label for="password" th:text="#{login.password}">passwordlabel>
<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、安全与授权
9.1、快速入门
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-securityartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<a th:href="@{/v/1}">v1a>
<a th:href="@{/v/2}">v2a>
<a th:href="@{/v/3}">v3a>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
v1
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>权限不足哦!h1>
body>
html>
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、配置类
@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、自定义认证接口
@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、自定义登录页(走)
@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>Titletitle>
head>
<body>
<form action="/login" method="post">
<label for="username">usernamelabel>
<input type="text" id="username" name="username" placeholder="usernamePlaceholder">
<label for="password">passwordlabel>
<input type="password" id="password" name="password" placeholder="passwordPlaceholder">
<input type="submit" value="login">
form>
body>
html>
9.4、授权
9.4.1、antMatchers
9.4.2、hasAuthority
@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
@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"));
}
}
@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
@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、退出登录
@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);
}
}
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>Titletitle>
head>
<body>
<a th:href="@{/v/1}">v1a>
<a th:href="@{/v/2}">v2a>
<a th:href="@{/v/3}">v3a>
<br>
<a href="/logout">退出登录a>
body>
html>
9.7、Thymeleaf整合Spring Security
<dependency>
<groupId>org.thymeleaf.extrasgroupId>
<artifactId>thymeleaf-extras-springsecurity5artifactId>
<version>3.0.4.RELEASEversion>
dependency>
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"(注意是这个)
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"(这个跟最新版本不匹配)
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>Titletitle>
head>
<body>
<a th:href="@{/v/1}">v1a>
<a th:href="@{/v/2}">v2a>
<a th:href="@{/v/3}">v3a>
<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.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
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)
0~59的整数
, - * / 四个字符
分(Minutes)
0~59的整数
, - * / 四个字符
小时(Hours)
0~23的整数
, - * / 四个字符
日期(DayofMonth)
1~31的整数(但是你需要考虑你月的天数)
,- * ? / L W C 八个字符
月份(Month)
1~12的整数或者 JAN-DEC
, - * / 四个字符
星期(DayofWeek)
1~7的整数或者 SUN-SAT (1=SUN)
, - * ? / L C # 八个字符
年(可选,留空)(Year)
1970~2099
, - * / 四个字符
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.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
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、邮件
11.1、依赖
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-mailartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
11.2、application.yaml
spring:
mail:
username: [email protected]
# 填写上你自己的密钥
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("[email protected]");
simpleMailMessage.setTo("[email protected]");
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("[email protected]");
mimeMessageHelper.setTo("[email protected]");
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.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<version>2.4.0version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
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", "[email protected]"))
.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、注意事项
spring.mvc.pathmatch.matching-strategy= ANT_PATH_MATCHER
13、文件上传下载
13.1、依赖
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
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>