SpringBoot2核心技术最好的一篇文章——2. 核心技术

一、配置文件

1.1 properties

同以前的properties一样使用方法

1.2 yaml

1. 简介

一种标语言

2. 基本语法

  • key: value ; k: v 之间⭐有空格
  • 大小写敏感;
  • 使用缩进表示层级关系
  • 缩进不允许使用tab, 只允许使用空格
  • 所进的空格数不重要,重要相同层级的元素左对齐就行
  • ‘#’ 表示注释
  • 单引号’’ 与双引号"" 表示字符内容为 转义/不转义

3. 数据类型

  • 字面量:单个的、不可再分的值。 date、 boolean、string、number、null
person:

# (字面量)
  userName: jzq
  boss: true
  birth: 2016/4/18
  age: 42
  • 对象: 键值对的集合。 map、hash、set、object
person:
# score: {name: 科比, num: 24}  (Map)
  score: {name: 科比, num: 24}

# salarys: (set)
  salarys:
    - 777.7
    - 24.08

# pet: (对象)
  pet:
    name: 弟弟
    weight: 25.2

# allPets:  (Map套集合)
  allPets:
    jx:
      - {name: 科比, weight: 170.5}
      - name: 库里
        weight: 145.5
    pt:
      - {name: 加索尔, weight: 215.5}
      - name: 普洱
        weight: 47.5



  • 数组: 一组按次序排列的值。 array、list、queue
person:

# interests: [篮球, 足球]  (数组)
  interests:
    - 篮球足球
    - 足球
    - 18
# animals: {科比, 库里}  (集合)
  animals: {科比, 库里}

1.3 配置处理器

pom中配置:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

记得在打包的时候不要打包:

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

二、 web开发

2.1 SpringMVC自动配置概览

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.(大多场景我们都无需自定义配置)
The auto-configuration adds the following features on top of Spring’s defaults:
● Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
○ 内容协商视图解析器和BeanName视图解析器
● Support for serving static resources, including support for WebJars (covered later in this document)).
○ 静态资源(包括webjars)
● Automatic registration of Converter, GenericConverter, and Formatter beans.
○ 自动注册 Converter,GenericConverter,Formatter
● Support for HttpMessageConverters (covered later in this document).
○ 支持 HttpMessageConverters (后来我们配合内容协商理解原理)
● Automatic registration of MessageCodesResolver (covered later in this document).
○ 自动注册 MessageCodesResolver (国际化用)
● Static index.html support.
○ 静态index.html 页支持
● Custom Favicon support (covered later in this document).
○ 自定义 Favicon
● Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
○ 自动使用 ConfigurableWebBindingInitializer ,(DataBinder负责将请求数据绑定到JavaBean上)
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
不用@EnableWebMvc注解。使用 @Configuration + WebMvcConfigurer 自定义规则

If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.
声明 WebMvcRegistrations 改变默认底层组件

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.
使用 @EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration 全面接管SpringMVC

2.2 简单的功能分析

1. 静态资源访问

静态资源目录

只要静态资源放在类路径下: /static 或者 / public 或者 /resources 或者 /META-INF/resources
在这些目录下的静态文件通过 当前项目根路径/ + 静态资源路径名即可访问

原理: 静态映射/**。
请求进来, 先去找controller看能不能处理,不能处理的所有请求都会交给静态资源处理器,静态资源能找到,就返回,静态资源如若也找不到,就返回404.

静态资源访问前缀

防止拦截器拦截静态文件,配置静态资源访问的前缀。

application.yaml配置文件

# 静态文件访问前缀
spring:
  mvc:
    static-path-pattern: /res/**

原本可以配置前置路径,就是配置非那四个 静态资源目录下的静态资源也可以被房屋,现在这个配置过时了。
在这里插入图片描述

2 欢迎页

静态资源路径下的index.html

静态路径下的 index.html

  1. 可以配置静态资源路径
  2. 但是不可以配置静态访问前缀,否则导致index.html不能被默认访问。
controller能处理/index

3. 自定义favicon

favicon.ico 放在静态资源目录下就行。

4. 静态资源配置原理(截图自尚硅谷雷老师)

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

5. 请求参数处理(截图自尚硅谷雷老师)

rest使用与原理

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

请求映射原理

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

普通参数与基本注解
注解

@Pathvariable、 @RequestHeader、 @ModelAttribute、@RequestParam、@MatrixVariable、 @CookieValue、 @RequestBody

⭐⭐讲解一下 @Pathvariable 与 @MatrixVariable

矩阵变量

⭐第一步配置config类
第一种配置config类

package jzq.com.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {

    /**
     * 修改 表单的请求方法(因为表单支持post、get, 若通过表单发送put方法的时候,需要指定的_m)
     * @return
     */
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        hiddenHttpMethodFilter.setMethodParam("_m");
        return  hiddenHttpMethodFilter;
    }


    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        // 不移除, 后面的内容。 矩阵变量就可以生效了
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

第二种配置config类

package jzq.com.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

@Configuration(proxyBeanMethods = false)
public class WebConfig {

    /**
     * 修改 表单的请求方法(因为表单支持post、get, 若通过表单发送put方法的时候,需要指定的_m)
     * @return
     */
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        hiddenHttpMethodFilter.setMethodParam("_m");
        return  hiddenHttpMethodFilter;
    }


	/**
     * 第二种实现矩阵变量的方案
     * @return
     */
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                configurer.setUrlPathHelper(urlPathHelper);
            }
        };
    }
}

⭐第二步 Controller类注解的使用

请求格式: @GetMapping("/test/{path}")
获取矩阵参数: @MatrixVariable
获取矩阵变量路径: @PathVariable


@MatrixVariable(“name”) List<String> names 接收多同名参数

 @GetMapping("/test/{path}")
    public Map test01(
            @MatrixVariable("age") Integer age,
            @MatrixVariable("name") List<String> names,
            @PathVariable("path") String path
    ) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("age", age);
        map.put("name", names);
        map.put("path", path);

        return map;
    }

⭐示例:
在这里插入图片描述

⭐ 假如同一请求有两个矩形变量,且两个请求有相同参数,可以区别取出它们所携带的参数值。

@GetMapping("/test2/{bossId}/{empId}")
    public Map test02(
            @MatrixVariable(value = "age", pathVar = "bossId") Integer boosAge,
            @MatrixVariable(value = "age", pathVar = "empId") Integer empAge,
            @PathVariable("bossId") String bossId,
            @PathVariable("empId") String empId
    ) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("boosAge", boosAge);
        map.put("empAge", empAge);
        map.put("bossId", bossId);
        map.put("empId", empId);
        return map;
    }

示例:
在这里插入图片描述

参数处理原理
自定义Converter

这个自定义的Converter能实现什么呢?
假如一个API的接收接收参数正巧是一个实体类,该实体类有一个参数是自定义对象,例如http://localhost:4547/ssss?age=15&person=dsdda,fss 中的person参数就是一个对象,该参数采用,分割传参,如何让控制器方法接受到这个参数的时候,为person属性赋值呢?

⭐Controller层

 @GetMapping("/ssss")
    public TestPerson test01(TestPerson testPerson) {
        System.out.println("sss");
        return testPerson;
    }

⭐ pojo代码

  1. person
package jzq.com.boot.pojo;

import lombok.Data;
import lombok.ToString;

@Data
@ToString
public class Person {

    private String name;
    private String dom;
}

  1. TestPerson
package jzq.com.boot.pojo;

import lombok.Data;
import lombok.ToString;

@Data
@ToString
public class TestPerson {
    private Person person;
    private int age;
}

⭐⭐在配置类中自定义Converter

重写public void addFormatters(FormatterRegistry registry){…}
在 registry.addConverter(new Converter<String, Person>() {…}添加Converter
这里的Converter指定了泛型↑,方法体内实现如下↓
@Override
public Person convert(String source) {… }
这里返回值类型为对象类型,接收参数为请求链接的携带对象参数(这里是,分割)

package jzq.com.boot.config;

import jzq.com.boot.pojo.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

@Configuration(proxyBeanMethods = false)
public class WebConfig /*implements WebMvcConfigurer*/ {

    /**
     * 修改 表单的请求方法(因为表单支持post、get, 若通过表单发送put方法的时候,需要指定的_m)
     * @return
     */
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        hiddenHttpMethodFilter.setMethodParam("_m");
        return  hiddenHttpMethodFilter;
    }

    /**
     * 第一种实现矩阵变量的方案
     * @param
     */
    //@Override
    //public void configurePathMatch(PathMatchConfigurer configurer) {
    //    UrlPathHelper urlPathHelper = new UrlPathHelper();
    //    // 不移除, 后面的内容。 矩阵变量就可以生效了
    //    urlPathHelper.setRemoveSemicolonContent(false);
    //    configurer.setUrlPathHelper(urlPathHelper);
    //}

    /**
     * 第二种实现矩阵变量的方案
     * @return
     */
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                configurer.setUrlPathHelper(urlPathHelper);
            }

            @Override
            public void addFormatters(FormatterRegistry registry) {
                registry.addConverter(new Converter<String, Person>() {
                    @Override
                    public Person convert(String source) {
                        System.out.println(source);
                        System.out.println("///");
                        if(!StringUtils.isEmpty(source)) {
                            Person person = new Person();
                            String[] split = source.split(",");
                            person.setName(split[0]);
                            person.setDom(split[1]);
                            return person;
                        }
                        return null;
                    }
                });
            }
        };
    }
}

6. 数据响应与内容协商

响应JSon
jackson.jar + @ResponseBody

这个三个dependency是一层一层引用的

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

<--! web自动引入json场景 --><dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-json</artifactId>
      <version>2.6.1</version>
      <scope>compile</scope>
</dependency>

<--! 一层一层--><dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jdk8</artifactId>
      <version>2.13.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jsr310</artifactId>
      <version>2.13.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-parameter-names</artifactId>
      <version>2.13.0</version>
      <scope>compile</scope>
    </dependency>
内容协商(接口返回json/xml/其他格式数据)

⭐导入jar

<dependency>
      <groupId>com.fasterxml.jackson.dataformat</groupId>
      <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

⭐配置文件内配置

# 开启内容协商
spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true
    contentnegotiation:
      favor-parameter: true

⭐请求示例

在请求上带上format=格式(例如json)
在这里插入图片描述
在这里插入图片描述

⭐⭐尚硅谷雷神笔记(雷神笔记

雷神视频讲解了很多框架源码与实现原理,由于个人时间问题,目前只需先学会应用,因此笔记不再记录,后续手撕源码时会再次补充,如有读者看笔记,直接点击雷神笔记,观看雷神记录的笔记!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值