基于 SpringBoot 2.4.5 版本
1. 快速入门
1.1 创建springboot项目
创建sprinboot项目有两种方式,可以选择去官网构建,Spring Initializr:https://start.spring.io/ ,默认构建的时maven项目,然后使用idea导入即可;还可以直接用idea创建,这里直接用idea创建项目。
通过上面步骤完成了基础项目的创建。就会自动生成以下文件。
其中entity、service、controller包是自己建的,默认一定要在主程序类(SpringbootApplication)的同级目录下,否则识别不到。
1.3 启动程序
运行主程序类就可以启动,默认是8080端口,打开浏览器输入http://localhost:8080/即可访问成功,访问的是默认页面Error Page
也可以编写一个index.html页面放在static目录下,那么就会访问index页面。
1.4 部署
导入maven插件,把项目打成jar包(默认就是jar包),直接在目标服务器执行即可。
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
1.5 彩蛋
更改启动时显示的字符拼成的字母,也就是 banner 图案:
到项目下的 resources 目录下新建一个banner.txt 即可。
图案可以到:https://www.bootschool.net/ascii 这个网站生成,然后拷贝到文件中即可!
2. 原理初探
2.1 主程序,原理初探
@SpringBootApplication // 标注主程序类,说明这是一个springboot应用
public class Springboot01Application {
public static void main(String[] args) {
SpringApplication.run(Springboot01Application.class, args);
}
}
@SpringBootApplication :标注在主程序类上,应该运行该类的mian方法来启动SpringBoot应用。
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
@SpringBootConfiguration :表示这是一个SpringBoot的配置类,底层使用@Configuration注解。
- @Configuration :Spring提供的注解,表示这是个配置类。
@EnableAutoConfiguration :开启SpringBoot的自动配置。
@ComponentScan :包扫描。
自动配置原理
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
@AutoConfigurationPackage :自动配置包,
- @Import(AutoConfigurationPackages.Registrar.class) :使用Spring提供的
@Import注解给IOC容器中导入一个包注册组件(AutoConfigurationPackages.Registrar.class)。@Import 也可以导入其他配置类。 - 该组件的作用就是将主配置类(@SpringBootApplication标注的类)所在的包及下面所有子包中的组件扫描并导入到IOC容器中。参考Spring注解底层原理。
@Import(AutoConfigurationImportSelector.class) :给容器中导入一些组件。通过参数指定。
- AutoConfigurationImportSelector.class:导入选择器,用来管理需要导入哪些组件。
- 会给容器中导入很多
xxxAutoConfiguration配置类,每个配置类都对应着一个特定功能,这些配置类会给容器中导入该场景下所需要的所有组件。 - 每个
xxxAutoConfiguration配置类都对应一个xxxProperties类,从该类中过去属性值,而该xxxProperties类由于配置文件绑定,利用属性绑定从配置文件中获取值。 - 有了自动配置类,就免去了我们手动编写配置和注入功能组件等工作。
2.2 常见注解
2.2.1 原生配置文件引入
@ImportResource
@Configuration
@ImportResource("classpath:beans.xml") // 引入自定义的配置文件
public class MyConfig {
}
2.2.2 实体属性绑定
读取到 .properties 配置文件中的内容,并且把它封装到JavaBean中。有两种方式。
1. @Component + @ConfigurationProperties
实体类
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
... // get、set方法
application.properties配置文件
mycar.brand=byd
mycar.price=10000
2. @EnableConfigurationProperties + @ConfigurationProperties
实体类
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
... // get、set方法
MyConbfig配置类
@Configuration
// 该注解必须标注在配置类上
// 有两个作用 1.开启属性绑定 2.注入容器中
@EnableConfigurationProperties(Car.class)
public class Myconfig{
}
3. 配置文件
SpringBoot使用一个全局的配置文件 , 配置文件名称是固定的。
- application.properties
- 语法结构 :key=value
- application.yaml
- 语法结构 :key: (空格) value
配置文件的作用 :修改SpringBoot自动配置的默认值,因为SpringBoot在底层都给我们自动配置好了。
比如我们可以在配置文件中修改Tomcat 默认启动的端口号!
server.port=8081
Tips:当两种配置文件同时存在时,.properties 优先。
3.1 ymal配置文件
yaml是一种标记语言,是springboot官方推荐使用的配置文件格式。这种语言以数据作为中心,而不是以标记语言为重点! yaml配置文件相比properties有很多优点。
例如使用yaml来配置tomcat端口
service:
port: 8081
3.2 yaml基本语法
说明:语法要求严格!
- 空格不能省略
- 以缩进来控制层级关系,只要是左边对齐的一列数据都是同一个层级的。
- 属性和值的大小写都是十分敏感的。
- ‘#’ 表示注释。
value是 普通的值 ( 数字,布尔值,字符串 )
格式:
key: value
# 例如
name: hao
注意 :
- 双引号(“ “):不会转义字符串里面的特殊字符 ,比如 :name: “hello \n world” 输出 :hello 换行 world。
- 单引号(‘ ’):会转义特殊字符 ,比如 :name: “hello \n world” 输出 :hello \n world
value是 对象、Map(键值对)
格式:
keyA:
KeyB1: value1
KeyB2: value2
# 例如
student:
name: hao
age: 20
行内写法:
student: {name: hao,age: 3}
value是 数组( List、set )
格式:
key:
- value1
- value2
# 例如
pets:
- cat
- dog
- pig
行内写法:
pets: [cat,dog,pig]
3.3 使用yaml给实体类注入属性值
yaml文件更强大的地方在于,他可以给我们的实体类直接注入匹配值。
使用该功能时导入以下依赖会有提示。与业务功能无关。打包时最好排除。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
下面给出一个示例
- 编写实体类
public class Dog {
private String name;
private Integer age;
//有参无参构造、get、set方法、toString()方法
}
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
//有参无参构造、get、set方法、toString()方法
}
- 编写配置类application.yaml
person:
name: hao
age: 3
happy: false
birth: 2000/01/01
maps: {k1: v1,k2: v2}
lists:
- code
- run
- music
dog:
name: haha
age: 1
- 注入属性值
/*
@ConfigurationProperties作用:将本类中的所有属性和配置文件中相关的配置进行绑定。
参数 prefix = “person” : 指定该实体类的配置信息
注意:
1. 该注解默认从全局配置文件中获取值。即application.yaml文件。
2. 该注解只有对已经加载进Spring容器中的组件有效。
3. 该注解也可以结合application.properties文件来使用。
*/
@Component //只有是容器中的组件,容器才会为 @ConfigurationProperties 提供此注入功能
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
//有参无参构造、get、set方法、toString()方法
}
加载指定的配置文件
@PropertySource : 加载指定的配置文件;只能用于properties配置文件,也可以结合@Value和@ConfigurationProperties来使用。
- 编写实体类
@Component
public class User {
private String name;
private int age;
private String sex;
}
- 编写user.properties文件
user1.name=haohao
user1.age=18
user1.sex=男
1. @PropertySource + @Value
@Component
@PropertySource (value = "classpath:user.properties")
public class User {
@value("${user1.name}")
private String name;
@Value("#{9*2}") // #{SPEL} Spring表达式
private int age;
@Value("男")
private String sex;
}
2. @PropertySource + @ConfigurationProperties
@Component
@PropertySource (value = "classpath:user.properties")
@ConfigurationProperties(prefix="user1")
public class User {
private String name;
private int age;
private String sex;
... // get、set方法
}
@Value获取值 和@ConfigurationProperties获取值 比较
| @ConfigurationProperties | @Value | |
|---|---|---|
| 功能 | 批量注入属性 | 单个属性绑定 |
| 松散绑定 | 支持 | 不支持 |
| SpEL | 不支持 | 支持 |
| JSR303数据校验 | 支持 | 不支持 |
| 复杂类型封装 | 支持 | 不支持 |
3.4 JSR303校验
当使用@ConfigurationProperties给对象注入属性值时,Springboot中可以用@validated来对注入的数据进行校验,如果数据异常则会统一抛出异常,方便异常中心统一处理。
例如写个注解让我们的name只能支持Email格式;
@Component
@ConfigurationProperties(prefix = "person")
@Validated //数据校验
public class Person {
@Email(message="邮箱格式错误") //email必须是邮箱格式
private String email;
}
使用数据校验,可以保证数据的正确性;
常见校验注解
@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则
...除此以外,我们还可以自定义一些数据校验规则
3.5 配置文件加载位置
springboot 启动会扫描以下位置的 application.properties 或者 application.yml 文件作为Spring boot的默认配置文件:
优先级1: jar包当前目录/config目录
优先级2: jar包当前目录
优先级3: classpath根路径/config目录
优先级4: classpath根路径 # 默认
优先级由高到底,高优先级的配置会覆盖低优先级的配置;
SpringBoot会从这四个位置全部加载主配置文件;互补配置。
4 Web开发
4.1 静态资源
4.1.1 静态资源存放位置
有以下几个目录可以用来存放静态文件。
访问地址http://localhost:8080/静态资源名
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"
原理: 静态映射是/**。
请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面。
拓展:还可以通过 webjars 方式引入静态资源
该方式以jar包的方式引入静态资源,需要使用到maven添加依赖,访问地址为http://localhost:8080/webjars/静态资源名
例如引入jQuery的资源,可以去webjars网站找到需要引入的依赖,然后就会以jar包的形式引入到项目中。访问时是使用http://localhost:8080/webjars/jquery/3.3.1/jquery.js。
注意:template目录下的所有资源只能通过controller来访问。
4.1.2 目录的优先级
/resources > /static(默认)> /public
源码分析
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
4.1.3 自定义静态资源目录
我们也可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置。
spring.resources.static-locations=classpath:/coding/, classpath:/hao/
一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了!
4.1.4 自定义静态资源访问前缀
静态资源的默认访问路径是/静态资源名。后面开发中会配置拦截器,默认拦截所有请求,那么此时静态资源也会被拦截,为了不让静态资源被拦截,可以给静态资源访问添加一个前缀,然后让拦截器不拦截该前缀开始的请求。
spring:
mvc:
static-path-pattern: /res/**
此时访问静态资源地址为/res/静态资源名
4.1.4 首页
- 静态资源路径下 index.html
静态资源文件夹下的所有 index.html 页面;被 / 映射。
访问 http://localhost:8080/ ,就会找静态资源文件夹下的 index.html。
新建一个 index.html ,放在上面的3个静态资源目录中的任意一个;然后访问测试 http://localhost:8080/ 。
此时不能配置静态资源前缀,否则首页会失效。
- 编写Controller映射/index
4.1.5 自定义Favicon
将 favicon.ico 放在静态资源目录下即可。
对于google浏览器可能失效,解决办法如下:
将 favicon.ico 放在静态资源目录下的 images 文件夹下,然后在页面中引用一下。
<link rel="icon" href="images/favicon.ico"/>
4.2 支持restful 风格
配置文件
spring: mvc: hiddenmethod: filter: enabled: true表单添加隐藏域
<!--method 的值必须是post --> <form action="/user" method="post"> <!-- 隐藏域。name="_method":固定写法,value:请求方式,支持get、post、delete、put --> <input type="hidden" name="_method" value="delete"> <input type="submit" value="delete提交"> </form>
源码分析
WebMvcAutoConfiguration自动配置类给容器中添加了 HiddenHttpMethodFilter 组件。
/**
@ConditionalOnMissingBean
容器中没有HiddenHttpMethodFilter类时才生效,意思是当我们自己配置了该类时,自动配置会失效。
@ConditionalOnProperty
该注解是条件注解,只有在配置文件中配置了 spring.mvc.hiddenmethod.filter.enabled = true 才会生效,默认是false。
*/
@Bean
@ConditionalOnMissingBean({HiddenHttpMethodFilter.class})
@ConditionalOnProperty(
prefix = "spring.mvc.hiddenmethod.filter",
name = {"enabled"},
matchIfMissing = false
)
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter();
}
4.3 请求映射原理
SpringMVC功能分析都从 DispatcherServlet —> doDispatch() 出发。
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception{
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
try {
ModelAndView mv = null;
Object dispatchException = null;
try {
processedRequest = this.checkMultipart(request);
multipartRequestParsed = processedRequest != request;
// 找到当前请求使用哪个Handler(对应Controller的方法)处理
mappedHandler = this.getHandler(processedRequest);
...
}
mappedHandler = this.getHandler(processedRequest); 源码
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
Iterator var2 = this.handlerMappings.iterator();
// 遍历所有的 HandlerMapping,里面封装着 请求-->处理器 的映射
while(var2.hasNext()) {
HandlerMapping mapping = (HandlerMapping)var2.next();
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
RequestMappingHandlerMapping:保存了所有 @RequestMapping 和 handler 的映射规则。
所有的请求映射都在HandlerMapping中。
- SpringBoot自动配置欢迎页的 WelcomePageHandlerMapping 。访问 /能访问到index.html;
- SpringBoot自动配置了默认 的 RequestMappingHandlerMapping
- 请求进来,挨个尝试所有的HandlerMapping看是否有请求信息。
- 如果有就找到这个请求对应的handler
- 如果没有就是下一个 HandlerMapping
- 我们需要一些自定义的映射处理,我们也可以自己给容器中放自定义的 HandlerMapping
4.4 请求参数与基本注解
4.4.1 基本注解
@RequestParam、@PathVariable、@RequestBody、@RequestHeader、@CookieValue、@ModelAttribute、@MatrixVariable
@RestController
public class ParameterTestController {
// car/2/owner/zhangsan
@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar(@PathVariable("id") Integer id,
@PathVariable("username") String name,
@PathVariable Map<String,String> pv,
@RequestHeader("User-Agent") String userAgent,
@RequestHeader Map<String,String> header,
@RequestParam("age") Integer age,
@RequestParam("inters") List<String> inters,
@RequestParam Map<String,String> params,
@CookieValue("_ga") String _ga,
@CookieValue("_ga") Cookie cookie){
return null;
}
}
4.4.2 自定义 Converter
在封装请求参数时,底层会使用很多 xxxToxxxConverter 进行数据类型转换。
Spring Boot2.0之后在自定义SpringMVC配置时推荐直接实现WebMvcConfigurer接口,里面的方法都是默认方法,可以通过重写需要的方法来实现自定义配置。自定义配置和默认配置都会生效。
@Configuration
public class MyMvcConfiguration implements WebMvcConfigurer {
/**
* 自定义Converter,将String转成Pet
* @param registry
*/
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new Converter<String,Pet>() {
@Override
public Pet convert(String s) {
if(!StringUtils.isEmpty(s)){
Pet pet = new Pet();
String[] split = s.split(",");
pet.setName(split[0]);
pet.setAge(Integer.parseInt(split[1]));
return pet;
}
return null;
}
});
}
}
此时请求参数 “tom,2” 会被转换成 Pet 类型。
idea重写方法快捷键:Ctrl+O
4.5 数据响应与内容协商
4.5.1 响应JSON
- jackson.jar+@ResponseBody
**
web 场景的启动器默认就引入了 json 场景
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<version>2.3.4.RELEASE</version>
<scope>compile</scope>
</dependency>
- 使用 @responseBody 注解给前端返回 json 数据;
返回值解析器
当返回数据时,底层是利用不同的HandlerMethodReturnValueHandler对返回的数据进行解析的。
对于标注了 @ResponseBody 注解的方法,使用的是 RequestResponseBodyMethodProcessor对返回值进行处理。
而该处理器底层利用 HttpMessageConverter 对返回值进行处理,将数据转成json格式,再写回给前端。这个过程中涉及到 内容协商。
内容协商**
- 浏览器默认会以请求头的方式告诉服务器他能接受什么样的内容类型(MediaType);
- 服务器最终根据自己自身的能力,决定服务器能生产出什么样内容类型的数据。
- SpringMVC会挨个遍历所有容器底层的 HttpMessageConverter(接口),看谁能处理?
- 得到 MappingJackson2HttpMessageConverter 可以将对象写为json
- 利用MappingJackson2HttpMessageConverter将对象转为json再写出去。
- SpringMVC会挨个遍历所有容器底层的 HttpMessageConverter(接口),看谁能处理?
- 服务器最终根据自己自身的能力,决定服务器能生产出什么样内容类型的数据。
4.5.2 HttpMessageConverter 原理
- HttpMessageConverter 规范

HttpMessageConverter: 看是否支持将此 Class类型的对象,转为MediaType类型的数据。
例子:Person对象转为JSON。或者 JSON转为Person。
**
- 默认的 HttpMessageConverter

内容协商有两种常用的协商策略,由ContentNegotiationManager(内容协商管理器)管理。**
- 基于请求头的内容协商(默认)
- 基于请求参数的内容协商(配置文件中开启才生效)
容器默认加载的协商策略:
**
使用浏览器发送请求时,没法改变请求头的媒体类型,但是可以使用基于请求参数的内容协商功能。
4.5.3 基于请求参数的内容协商
引入依赖(支持返回xml媒体类型的数据)
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency>开启请求参数的内容协商功能
spring: mvc: contentnegotiation: favor-parameter: true #开启请求参数内容协商模式发请求:
**
format 为固定写法,取值 [ json、xml ] 。
4.5.4 自定义 HttpMessageConverter
每个 HttpMessageConverter 都有自己支持的媒体类型的数据,比如 MappingJackson2HttpMessageConverter 把对象转为JSON;MappingJackson2XmlHttpMessageConverter 把对象转为XML。
当想要返回自定义的媒体类型的数据,就需要自定义 HttpMessageConverter。
编写 MyHttpMessageConverter,实现
HttpMessageConverter接口public class MyHttpMessageConverter implements HttpMessageConverter { // 支持读哪些 mediaType 类型的数据,当请求参数用了 @ResponseBody 时使用 @Override public boolean canRead(Class aClass, MediaType mediaType) { return false; } // 支持读哪些 mediaType 类型的数据 @Override public boolean canWrite(Class aClass, MediaType mediaType) { return aClass.isAssignableFrom(Pet.class); } // 返回支持的 mediaType 类型 @Override public List<MediaType> getSupportedMediaTypes() { return MediaType.parseMediaTypes("application/hao"); } // 读然后转换 @Override public Object read(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException { return null; } // 按照自定义的格式转换并写出 @Override public void write(Object o, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException { Pet pet = (Pet)o; String result = pet.getName()+";"+pet.getAge()+";"; OutputStream outputStream = httpOutputMessage.getBody(); outputStream.write(result.getBytes()); } }配置
@Configuration public class MyMvcConfiguration implements WebMvcConfigurer { /** * 配置自定义 HttpMessageConverter * @param converters */ @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new MyHttpMessageConverter()); } }使用 PostMan 修改 Accept: application/hao,再发送请求 http://localhost:8080/pet。
上面说过基于请求参数的内容协商,请求参数 format 默认取值只能是 [ json、xml],那如何使用浏览器发送 hao 的请求呢?
可以自定义内容协商的策略
4.5.5 自定义内容协商策略
通过 WebMvcConfigurer 自定义 ```java @Configuration public class MyMvcConfiguration implements WebMvcConfigurer {
/**
- 自定义 ContentNegotiationStrategy(请求协商策略)
@param configurer */ @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { // 设置可选择的 参数值 HashMap
mediaTypeHashMap = new HashMap<>(); mediaTypeHashMap.put(“json”, MediaType.parseMediaType(“application/json”)); mediaTypeHashMap.put(“xml”, MediaType.parseMediaType(“application/xml”)); mediaTypeHashMap.put(“hao”, MediaType.parseMediaType(“application/hao”)); // 配置基于请求参数的内容协商策略 ParameterContentNegotiationStrategy parameterStrategy = new ParameterContentNegotiationStrategy(mediaTypeHashMap); parameterStrategy.setParameterName(“strategy”); // 设置请求参数的参数名为 strategy // 配置基于请求头的内容协商策略 HeaderContentNegotiationStrategy headerStrategy = new HeaderContentNegotiationStrategy(); configurer.strategies(Arrays.asList(parameterStrategy,headerStrategy)); }
浏览器发送请求 [http://localhost:8080/pet?strategy=hao](http://localhost:8080/pet?strategy=hao)
**注意:**通过重写 `WebMvcConfigurer->configureContentNegotiation()`方法来自定义请求协商策略,那么springboot默认的协商策略配置就会失效。
<a name="ArRZm"></a>
## 4.6 视图解析与模板引擎
视图解析:**SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染。**
<a name="uDL8S"></a>
### 4.6.1 视图解析
**视图解析原理流程**<br />**
- **任何目标方法执行完成以后都会返回 ModelAndView(数据和视图地址)。**
- **`DispatcherServlet->``processDispatchResult()->render(mv, request, response)` 处理派发结果(页面改如何响应)。**进行页面渲染逻辑
- `view = resolveViewName()`,根据视图名解析得到**View**对象【**View**定义了页面的渲染逻辑】
- 1、所有的视图解析器(**ViewResolver**)尝试是否能根据当前返回值得到**View**对象

- 2、ContentNegotiationViewResolver 解析得到 **ThymeleafView对象**
- ContentNegotiationViewResolver 里面包含了下面所有的视图解析器,内部还是利用下面所有视图解析器得到视图对象。
- 3、`view.render(mv.getModelInternal(), request, response)`; 视图对象调用自定义的render进行页面渲染工作
<a name="EGv9s"></a>
### 4.6.2 模板引擎-Thymeleaf
Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.<br />**现代化、服务端Java模板引擎**
<a name="KAnoG"></a>
###
<a name="mfetG"></a>
#### 1 基本语法
1. ** 表达式**
| **表达式名字** | **语法** | **用途** |
| :---: | :---: | :---: |
| 变量取值 | ${...} | 获取请求域、session域、对象等值 |
| 选择变量 | *{...} | 获取上下文对象值 |
| 消息 | #{...} | 获取国际化等值 |
| 链接 | @{...} | 生成链接 |
| 片段表达式 | ~{...} | jsp:include 作用,引入公共页面片段 |
2. **字面量**
文本值: **'one text' , 'Another one!' ,…**数字: **0 , 34 , 3.0 , 12.3 ,…**布尔值: **true , false**<br />空值: **null**<br />变量: one,two,.... 变量不能有空格
3. **文本操作**
字符串拼接: **+**<br />变量替换: **|The name is ${name}| **
4. **数学运算**
运算符: + , - , * , / , %
5. **布尔运算**
运算符: **and , or**<br />一元运算: **! , not **
6. **比较运算**
比较: **> , < , >= , <= ( gt , lt , ge , le )**等式: **== , != ( eq , ne ) **
7. **条件运算**
If-then: **(if) ? (then)**<br />If-then-else: **(if) ? (then) : (else)**<br />Default: **(value) ?: (defaultvalue) **
8. **特殊操作**
无操作: _
<a name="w82o5"></a>
#### 2 设置属性值-th:attr
设置单个值
```html
<form action="subscribe.html" th:attr="action=@{/subscribe}">
<fieldset>
<input type="text" name="email" />
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
</fieldset>
</form>
设置多个值
<img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
以上两个的代替写法 th:xxxx
<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
<form action="subscribe.html" th:action="@{/subscribe}">
所有h5兼容的标签写法
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes
3 迭代
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock} ? #{true} : #{false}">yes</td>
</tr>
4 条件运算
<a href="comments.html"
th:href="@{/product/comments(prodId=${prod.id})}"
th:if="${not #lists.isEmpty(prod.comments)}">view</a>
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
5 属性优先级

4.6.3 Thymeleaf 初体验
SpringBoot 自动配置好了 thymeleaf
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {}
自动配好的策略
- 1、所有 thymeleaf 的配置值都在 ThymeleafProperties
- 2、配置好了 SpringTemplateEngine
- 3、配好了 ThymeleafViewResolver
- 4、我们只需要直接开发页面
public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; //xxx.html
使用 Thymeleaf 的步骤:
- 导入 starter
- 编写 Controller
页面开发
导入 stater
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>编写 Controller
@Controller public class TestViewController { @RequestMapping("/hao") public String hao(Model model){ model.addAttribute("msg", "你好"); model.addAttribute("link", "http://www.baidu.com"); return "success"; } }页面开发
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 th:text="${msg}">哈哈</h1> <h2> <a href="http://www.baidu.com" th:href="${link}">去百度</a> <br/> <a href="http://www.baidu.com" th:href="@{/hao}">去contorller</a> </h2> </body> </html>
4.6.4 构建后台管理系统
4.7 拦截器
4.7.1 自定义拦截器
定义拦截器实现 HandlerInterceptor 接口
public class LoginInterceptor implements HandlerInterceptor { // 目标方法执行只前执行 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("检查是否登录"); return true; } // 目标方法执行之后执行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("目标方法执行完成"); } // 页面渲染之后执行 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("页面渲染完成"); } }配置拦截器
@Configuration public class MyMvcConfiguration implements WebMvcConfigurer { /** * 添加自定义拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/**") //所有请求都被拦截包括静态资源 .excludePathPatterns("/login","/statics/**"); // 放行的请求 } }拦截器拦截所有请求时,包括所有的静态资源也会被拦截,此时需要排除所有的静态资源。
可以通过配置静态资源前缀来排除所有的静态资源/statics/**
4.7.2 拦截器原理
1、根据当前请求,找到HandlerExecutionChain【可以处理请求的handler以及handler的所有 拦截器】
2、先来顺序执行 所有拦截器的 preHandle方法
- 1、如果当前拦截器prehandler返回为true。则执行下一个拦截器的preHandle
- 2、如果当前拦截器返回为false。直接 倒序执行所有已经执行了的拦截器的 afterCompletion;
3、如果任何一个拦截器返回false。直接跳出不执行目标方法
4、所有拦截器都返回True。执行目标方法
5、倒序执行所有拦截器的postHandle方法。
6、前面的步骤有任何异常都会直接倒序触发 afterCompletion
7、页面成功渲染完成以后,也会倒序触发 afterCompletion
4.8 文件上传
4.8.1 文件上传示例
页面表单
<form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="img"><br> <!-- 单文件上传 --> <input type="file" name="photos" multiple="multiple"><br> <!-- 多文件上传 --> <input type="submit" value="提交"> </form>文件上传
@Controller public class FileUploadContorller { @RequestMapping("/upload") @ResponseBody public String fileUpload(@RequestParam(required = false) String name, @RequestPart(value = "img") MultipartFile image, @RequestPart(value = "photos") MultipartFile[] photos) throws IOException { // 保存单文件 if(!image.isEmpty()){ String imageName = image.getOriginalFilename(); image.transferTo(new File("D:\\images\\"+imageName)); } // 保存多文件 if(photos.length>0){ for (MultipartFile photo: photos) { if(!photo.isEmpty()){ String originalFilename=photo.getOriginalFilename(); photo.transferTo(new File("D:\\images\\"+originalFilename)); } } } return "haha"; } }
文件的默认最大单个文件大小不超过1MB,总上传文件数据大小不超过10MB,这个数据大小可以在配置文件中更改
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
4.8.2 自动配置原理
文件上传自动配置类 **MultipartAutoConfiguration**,关联的配置类 **MultipartProperties**
- 自动配置好了 StandardServletMultipartResolver 【文件上传解析器】
- 原理步骤
- 1、使用文件上传解析器判断(isMultipart)并封装(resolveMultipart,返回MultipartHttpServletRequest)文件上传请求
- 2、参数解析器来解析请求中的文件内容封装成 MultipartFile
- 3、将request中文件信息封装为一个Map;MultiValueMap
使用到的参数解析器:
4.9 异常处理
4.9.1 默认规则
- 默认情况下,Spring Boot提供
/error处理所有错误的映射 - 对于机器客户端(比如使用PostMan),它将生成JSON响应,其中包含错误,HTTP状态和异常消息的详细信息。对于浏览器客户端,响应一个“ whitelabel”错误视图,以HTML格式呈现相同的数据。


可以自定义错误页面:
- error/ 下的4xx,5xx 页面会被自动解析;
json里的数据可以在页面获取。
<h2 th:text="${status}">OOOPS!!!</h2>
<h3 th:text="${message}">Something went wrong.</h3>
4.9.4 异常处理自动配置原理
异常处理的自动配置是 **ErrorMvcAutoConfiguration**。容器中配置了很多组件
DefaultErrorAttributes- public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered { }
- 本身也是一个 HandlerExceptionResolver,定义了错误页面中可以包含哪些数据
BasicErrorController- 处理默认 /error 路径的请求;页面响应 new ModelAndView(“error”, model)
View(默认的错误视图)- 视图的 name=error,用于响应默认的错误页。
BeanNameViewResolver(视图解析器)- 按照返回的视图名作为组件的id去容器中找View对象。
- (json+白页 适配响应)
DefaultErrorViewResolver- 如果发生错误,会以HTTP的状态码 作为视图页地址(viewName),找到真正的页面。
- error/ 4xx.html、5xx.html
- 自定义 错误页面的解析器
异常解析流程
- 目标方法抛出异常,被catch ->执行 processDispatchResult->processHandlerException
- 遍历所有的 HandlerExceptionResolvers,看谁能处理当前异常【**HandlerExceptionResolver处理器异常解析器**】
- 系统默认的 异常解析器;

- 1、DefaultErrorAttributes先来处理异常。把异常信息保存到request域,并且返回null。
- 2、默认没有任何人能处理异常,所以异常会被抛出。
- 1、如果没有任何人能处理最终底层就会发送 /error 请求。会被底层的BasicErrorController处理,页面响应 **new ModelAndView(“error”, model)**
- 2、解析错误视图;遍历所有的 **ErrorViewResolver **看谁能解析。

- 3、默认的 **DefaultErrorViewResolver ,作用是把响应状态码作为错误页的地址,error/500.html **
- 4、模板引擎最终响应这个页面 error/500.html
4.9.3 自定义错处处理规则
1 自定义错误页面
error/ 404.html error/ 5xx.html;有精确的错误状态码页面就匹配精确,没有就找 4xx.html;如果都没有就触发白页。没有HandlerExceptionResolver** 能够处理,tomcat 发送 /error 请求。**
2 @ControllerAdvice+@ExceptionHandler 处理全局异常
这是SpringMVC提供的功能。
使用@ControllerAdvice标注类,在该类中,可以定义多个方法,不同的方法处理不同的异常。@ExceptionHandler注解用来指明异常的处理类型。
@ControllerAdvice
public class GlobalException {
@ExceptionHandler({ArithmeticException.class, NullPointerException.class}) // 能够处理哪些异常
@ResponseBody
public String ArithExceptionHandler(Exception exception){
String message = exception.getMessage();
System.out.println(message);
return message;
}
}
底层使用的是 **ExceptionHandlerExceptionResolver (处理器异常解析器)**
3 @ResponseStatus+自定义异常
会以指定的 HTTP状态码 和指定的 reason 响应到浏览器;
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "测试自定义异常")
public class MyException extends RuntimeException {
public MyException() {
}
public MyException(String message) {
super(message);
}
}
底层使用的是 **ResponseStatusExceptionResolver (处理器异常解析器)**
还有 Spring 底层的异常,如 参数类型转换异常等,DefaultHandlerExceptionResolver**(处理器异常解析器)** 处理框架底层的异常。
4.10 Web原生组件注入(Servlet、Filter、Listener)
4.10.1 使用注解发方式
@WebServlet(urlPatterns = "/my"):效果:直接响应,没有经过Spring的拦截器,应为没有经过 DispatcherServlet@WebFilter(urlPatterns = {"/css/*","/images/*"})@WebListener
以上三个注解都需要与下面的注解结合使用。@ServletComponentScan(basePackages = "com.hao"):指定原生Servlet组件都放在那里。
4.10.2 使用RegistrationBean
ServletRegistrationBean, FilterRegistrationBean, and ServletListenerRegistrationBean
@Configuration
public class MyRegistConfig {
@Bean
public ServletRegistrationBean myServlet(){
MyServlet servlet = new MyServlet();
return new ServletRegistrationBean(myServlet,"/my","/my02");
}
@Bean
public FilterRegistrationBean myFilter(){
MyFilter filter = new MyFilter();
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
return filterRegistrationBean;
}
@Bean
public ServletListenerRegistrationBean myListener(){
MyServletContextListener listener = new MyServletContextListener();
return new ServletListenerRegistrationBean(mySwervletContextListener);
}
}
当多个 Servlet 都能处理到同一层路径,精确优选原则,选择 B
A: /my/
B: /my/1
4.11 嵌入式Servlet容器
SpringBoot包含对嵌入式Tomcat,Jetty和Undertow服务器的支持。默认使用Tomcat作为嵌入式的Servlet容器。**
原理:
- SpringBoot应用启动发现当前是Web应用。web场景包-导入tomcat。
- web应用会创建一个web版的ioc容器
ServletWebServerApplicationContext ServletWebServerApplicationContext容器启动的时候寻找ServletWebServerFactory。SpringBoot底层默认有很多的WebServer工厂;TomcatServletWebServerFactory,JettyServletWebServerFactory, orUndertowServletWebServerFactory

- 底层直接会有一个自动配置类
ServletWebServerFactoryAutoConfiguration,该自动配置类导入了ServletWebServerFactoryConfiguration(配置类),配置类判断系统中到底导入了那个Web服务器的包。(默认是web-starter导入tomcat包),容器中就有TomcatServletWebServerFactory。 TomcatServletWebServerFactory创建出Tomcat服务器并启动。TomcatWebServer的构造器拥有初始化方法initialize()---this.tomcat.start();

