一、Web开发
1、自动配置概览
1、Spring Boot provides auto-configuration for Spring MVC that works well with
most applications
翻译:
SpringBoot为SpringMVC提供了自动配置,可用于大多数应用程序
2、The auto-configuration adds the following features on top of Spring’s defaults:
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
翻译:
自动配置在Spring默认设置的基础上添加了以下功能:
包含ContentNegotingViewResolver和BeanNameViewResolver bean。
3、Support for serving static resources, including support for WebJars (covered later in this document)).
翻译:
对服务静态资源的支持,包括对WebJAR的支持(本文档后面将介绍)。
4、Support for HttpMessageConverters (covered later in this document).
翻译:
对HttpMessageConverters的支持(本文档后面将介绍)。
5、Automatic registration of MessageCodesResolver (covered later in this document).
翻译:
MessageCodesResolver的自动注册(本文档后面将介绍)。
6、Static index.html support
翻译:
静态index.html支持
7、Custom Favicon support (covered later in this document).
翻译:
自定义Favicon支持(本文档稍后将介绍)。
8、Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
翻译:
自动使用可配置的WebBindingInitializerbean(本文档后面将介绍)。
9、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.
翻译:
如果您想保留这些Spring Boot MVC定制并进行更多MVC定制(拦截器、格式化程序、视图控制器和其他功能),您可以添加自己的WebMVCConfiguer类型的@Configuration类,但不添加@EnableWebMvc。不用@EnableWebMvc注解。使用@Configuration
+WebMvcConfigurer
自定义规则
10、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.
翻译:
如果您想提供RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定义实例,并且仍然保留Spring Boot MVC自定义设置,那么可以声明WebMVCreRegistrations类型的bean,并使用它来提供这些组件的自定义实例。声明WebMvcRegistrations
改变默认底层组件11、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.
翻译:
如果您想完全控制SpringMVC,可以添加自己的@Configuration,并用@EnableWebMvc注释,或者添加自己的@Configuration注释的delegatingWebMVC配置,如@EnableWebMvc的Javadoc中所述。
2、静态资源规则与定制化
(1)pom 文件:
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<groupId>org.apache.springboot</groupId>
<artifactId>springboot-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-web</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-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.2.2.RELEASE</version>
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
在该文件目录下存放图片:
启动主程序类,访问:http://localhost:8080/bug.jpg
说明:可以根据静态文件目录直接访问
但是,如果配置了以下参数,他就无法直接访问的,还需要追加路径名才可以访问,如下:
spring:
mvc:
static-path-pattern: /res/**
当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找
访问报404错误:http://localhost:8080/bug.jpg
需要追加文件名才可以访问:http://localhost:8080/res/bug.jpg
另一种静态资源访问配置:表示改变静态资源文件
resources:
static-locations: [classpath:/public/]
文件目录:
(2)自动映射
<!-- https://mvnrepository.com/artifact/org.webjars.bower/jquery -->
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
静态资源路径:
访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径
3、欢迎页支持
(1)静态资源路径下 index.html
- 可以配置静态资源路径
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>SpringBoot Web ,欢迎你</h1>
</body>
</html>
前提条件:需要把静态资源的配置注释掉,保留locations配置即可
#spring:
# mvc:
# static-path-pattern: /res/**
#
resources:
static-locations: [classpath:/public/]
原因:controller能处理/index
说明:但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问
欢迎页的处理规则
HandlerMapping:处理器映射。保存了每一个Handler能处理哪些请求。
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
return welcomePageHandlerMapping;
}
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
//要用欢迎页功能,必须是/**
logger.info("Adding welcome page: " + welcomePage.get());
setRootViewName("forward:index.html");
}
else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
// 调用Controller /index
logger.info("Adding welcome page template: index");
setRootViewName("index");
}
}
debug测试
发现它是从容器拿出来的参数有
用ctrl+n,搜索“WelcomePageHandlerMapping” debug测试
4、自定义 Favicon
spring:
# mvc:
# static-path-pattern: /res/** 这个会导致 Favicon 功能失效
5、静态资源配置原理
(1)SpringBoot启动默认加载 xxxAutoConfiguration 类(自动配置类)
(2)SpringMVC功能的自动配置类 WebMvcAutoConfiguration,生效
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
给容器中配了什么?
@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}
配置文件的相关属性和xxx进行了绑定。WebMvcProperties==spring.mvc、ResourceProperties==spring.resources
(3)配置类只有一个有参构造器
//有参构造器所有参数的值都会从容器中确定
//ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
//WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
//ListableBeanFactory beanFactory Spring的beanFactory
//HttpMessageConverters 找到所有的HttpMessageConverters
//ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。=========
//DispatcherServletPath
//ServletRegistrationBean 给应用注册Servlet、Filter....
public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
ObjectProvider<DispatcherServletPath> dispatcherServletPath,
ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
this.resourceProperties = resourceProperties;
this.mvcProperties = mvcProperties;
this.beanFactory = beanFactory;
this.messageConvertersProvider = messageConvertersProvider;
this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
this.dispatcherServletPath = dispatcherServletPath;
this.servletRegistrations = servletRegistrations;
}
有参构造器所有参数的值都会从容器中确定
ResourceProperties resourceProperties | 获取和spring.resources绑定的所有的值的对象 |
WebMvcProperties mvcProperties | 获取和spring.mvc绑定的所有的值的对象 |
ListableBeanFactory beanFactory | Spring的beanFactory |
HttpMessageConverters | 找到所有的HttpMessageConverters |
ResourceHandlerRegistrationCustomizer | 找到 资源处理器的自定义器 |
DispatcherServletPath | |
ServletRegistrationBean | 给应用注册Servlet、Filter.... |
(4)资源处理的默认规则
@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();
//webjars的规则
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));
}
}
打debug测试
表明,它是先获取这三个参数
resourceProperties是一个构造器,我们知道构造器它会从容器中拿数据
它拿到spring.resources配置文件下绑定了配置的容器
所以,我们可以尝试配置这个参数:【默认参数为true】
resources:
add-mappings: false 禁用所有静态资源规则
cache:
period: 11000 #缓存时间,单位:秒
这个参数的作用,表示禁用所有的静态资源,不管放在哪个文件目录都无法访问