四、Web开发
1、简介
使用SpringBoot
1、创建SpringBoot应用,选中我们需要的模块
2、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3、自己编写业务代码;
了解自动配置原理
这个场景中SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?xxx
xxxxAutoConfiguration : 帮我们给容器中自动配置组件
xxxxProperties : 配置类来封装配置文件的内容;
2、SpringBoot对静态资源的映射规则;
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties {
1、所有/webjars/**,都去classpath:/META-INF/resources/webjars/找资源;
webjars:以jar包的方式引入静态资源;
http://www.webjars.org/
localhost:8080/webjars/jquery.3.3.1/jquery.js
<!-- 引入jquery-webjar-->在访问的时候只需要些webjars下面资源的名称即可
<dependency>
<groupId>org.webjar</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
2、“/**”访问当前项目的任何资源,(静态资源的文件夹)
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public"
"/"当前项目的根路径
localhost:8080/abc === 去静态资源文件夹里面找abc
3、欢迎页;静态资源文件夹下所有index.html页面;被“/**”映射;
localhost:8080/ 找index页面
4、所有的**/favicon.ico 都是在静态资源文件下找;
3、SpringMVC自动配置
Spring Boot自动配置好了SpringMVC
1、以下是SpringBoot对SpringMVC的默认配置:
-
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans
- 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(是转发还是重定向))
- ContentNegotiatingViewResolver:组合所有的视图解析器的;
- 如何定制:我们可以结合自己给容器中添加一个视图解析器;自动的将其组合进来;
-
Support for serving static resources,including support for Webjars (see below)。静态资源文件夹路径,webjars
-
Static index.html support,静态资源访问
-
Custom Favicon support (see blow),favicon.ico
-
自动注册了 of Converter,GenericConverter,Formatter beans,
-
Converter : 转换器 ;public String hello(User user) ;类型转换使用Converter
-
Farmatter : 格式化器; 2017.12.17 === Date ;
@Bean @ConditionalOnproperty(prefix="spring.mvc", name = "date-format")//在文件中配置日期格式的规则 public Formatter<date> dateFormatter(){ return new DateFormatter(this.mvcProperties.getDateFormat())//日期格式化组件 }
自己添加的格式化器转换器,我们只需要放在容器中即可
-
-
Support for HttpMessageConverters(see below)。
-
HttpMessageConverter : SpringMVC用来转换Http请求和响应的; User–json;
-
HttpMessageConverters : 是从容器中确定 ; 获取所有的HttpMessageConverter;
自己给容器中添加HttpMessageConverter,只需要将自己的组件注册到容器中(@Bean,@Componet)
-
-
Automatic registration of MessageCodesResolver(see below)定义错误代码
-
Automatic use of a ConfigurableWebBindingInitializer bean (see blow)
我们可以配置一个ConfigurableWebBindingIntializer来替换默认的;(添加到容器)
初始化WebDateBinder 请求数据 ======JavaBean
org.springframework.boot.autoconfigure.web:web的所有自动配置场景
2、扩展SpringMVC
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc;
既保留了所有的自动配置,也能用我们扩展的配置;
原理:
1、WebMvcAutoConfiguration是SpringMVC的自动配置类
2、在做其他自动配置时会导入 ; @Import(EnableWebMvcConfiguration.class)
3、容器中所有的WebMvcConfigurer都会一起起作用;
4、我们的配置类也会被调用;
效果:SpringMVC的自动配置和我们的扩展配置都会起作用;
3、全面接管SpringMVC;
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配;所有的SpringMVC的自动配置都失效了。
我们需要在配置类中添加@EnableWebMvc
4、如何修改SpringBoot的默认配置
模式:
1、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
2、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置