1、简介

使用SpringBoot:

  1. 创建SpringBoot应用,选中我们需要的模块;
  2. SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
  3. 自己编写业务逻辑;

自动配置原理

  1. xxxxAutoConfiguration:帮我们给容器中自动配置组件
  2. xxxxProperties:配置类来封装配置文件的内容

2、SpringBoot对静态资源的映射规则

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
// 可以设置和静态资源有关的参数,缓存时间等
        @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));
            }
        }


        // 来配置欢迎页的映射
        @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;
        }

1、所有/webjars/**,都去classpath:/META-INF/resources/webjars/找资源;

webjars:以jar包的方式引入静态资源;

http://www.webjars.org/

image-20201013194221927.png

localhost:8080/webjars/jquery/3.3.1/jquery.js

<!--
引入jQuery的webjar
在访问的时候只需要写webjars下面资源的名称即可
-->
<dependency>
    <groupId>org.webjars</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都是在静态资源文件下找的。

更改静态文件映射路径:

在application.properties文件中配置

#spring.resources.static-locations=classpath:/hello/,classpath:/zh/

3、模板引擎

JSP、Velocity、Freemarker、Thymeleaf

image-20201014202900834.png

SpringBoot推荐的Thymeleaf;

语法更简单,功能更强大;

1、引入thymeleaf

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--关于这儿的版本的问题:选用新的版本没有问题-->

2、Thymeleaf使用

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

    private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

    public static final String DEFAULT_PREFIX = "classpath:/templates/";

    public static final String DEFAULT_SUFFIX = ".html";

根据自动的Thymeleaf装配规则,只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

使用:

1、导入thymeleaf的名称空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2、使用thymeleaf语法:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功!</h1>
    <!‐‐th:text 将div里面的文本内容设置为 ‐‐>
    <div id="div01" class="myDiv" th:class="${hello}" th:id="${hello}" th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>

3、语法规则

1、th:text;改变当前元素里面的文本内容

th:任意html属性;来替换原生属性的值

image-20201014202707033.png

2、表达式

Simple expressions:
    Variable Expressions: ${...}:获取变量值
        1、 获取对象的属性,调用方法
        2、 使用内置的基本对象:
            #ctx : the context object.
            #vars: the context variables.
            #locale : the context locale.
            #request : (only in Web Contexts) the HttpServletRequest object.
            #response : (only in Web Contexts) the HttpServletResponse object.
            #session : (only in Web Contexts) the HttpSession object.
            #servletContext : (only in Web Contexts) the ServletContext object.
            ${session.foo}
        3、内置的一些工具对象:
            #execInfo : information about the template being processed.
            #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
            #uris : methods for escaping parts of URLs/URIs
            #conversions : methods for executing the configured conversion service (if any).
            #dates : methods for java.util.Date objects: formatting, component extraction, etc.
            #calendars : analogous to #dates , but for java.util.Calendar objects.
            #numbers : methods for formatting numeric objects.
            #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
            #objects : methods for objects in general.
            #bools : methods for boolean evaluation.
            #arrays : methods for arrays.
            #lists : methods for lists.
            #sets : methods for sets.
            #maps : methods for maps.
            #aggregates : methods for creating aggregates on arrays or collections.
            #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
    Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样的;
        补充:配合th:object="${session.user}":
        <div th:object="${session.user}">
            <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
            <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
            <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
        </div>

    Message Expressions: #{...}:来获取国际化的内容
    Link URL Expressions: @{...}:定义URL;
        @{/order/process(execId=${execId},execType='FAST')}
    Fragment Expressions: ~{...}:片段引用的表达式
        <div th:insert="~{commons :: main}">...</div>
Literals(字面量)
    Text literals: 'one text' , 'Another one!' ,…
    Number literals: 0 , 34 , 3.0 , 12.3 ,…
    Boolean literals: true , false
    Null literal: null
    Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(布尔运算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:(条件运算(三元运算符))
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:(特殊操作)
    No-Operation: _

4、SpringMVC自动配置

https://docs.spring.io/spring-boot/docs/2.3.4.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications

1、Spring MVC Auto-configuration

Spring Boot自动配置好了SpringMVC

以下是Spring Boot对SpringMVC的默认:

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
    • 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?))
    • ContentNegotiatingViewResolver:组合所有的视图解析器的;
    • 如何制定:我们可以自己给容器中添加一个视图解析器,自动的将其组合进来;
  • Support for serving static resources, including support for WebJars (covered later in this document)).静态资源文件夹路径webjars
  • 自动注册了 of Converter, GenericConverter, and Formatter beans.
    • Converter:转换器;public String hello(User user):类型转换使用Converter
    • Formatter:格式转化器:2020-10-14===Date;
@Bean
@ConditionaOnProperty(prfix = "spring.mvc", name = "date-format") // 在文件中配置日期格式化规则
public Formatter<Date> dateFormatter() {
    return new DateFormatter(this.mvcProperties.getDateFormat()); // 日期格式化组件
}
    自己添加的格式化器,我们只需要放在容器中即可
  • Support for HttpMessageConverters (covered later in this document).
    • HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User—json;
    • HttpMessageConverters:是从容器中确定;获取所有的HttpMessageConverter;
    • 自己给容器中添加HttpMessageConverter,只需要将自己的组件注册在容器中即可(@Bean,@Component)
  • Automatic registration of MessageCodesResolver (covered later in this document).定义错误代码的生成规则
  • Static index.html support. 静态首页访问
  • Custom Favicon support (covered later in this document).favicon.ico
  • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
    我们可以配置一个ConfigurationWebBindingInitializer来替换默认的;【添加到容器中】
    初始化WebDataBinder
    请求数据====JavaBean;
    

org.springframework.boot.autoconfigure.web:web的所有自动场景

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.

2、扩展SpringMVC

<mvc:view-controller path="/hello" view-name="success"/>
<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/hello"/>
        <bean></bean>
    </mvc:interceptor>
</mvc:interceptors>

编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc;

既保留了所有的自动配置,也能用我们扩展的配置

/**
 * @author cai-xiansheng
 * @Description 使用WebMvcConfigurer来扩展SpringMVC的功能
 * @create 2020-10-15 18:51
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 浏览器发送 /zh 也来到success来到页面
        registry.addRedirectViewController("/zh", "success");
    }
}

原理:

1、WebMvcAutoConfiguration是SpringMVC的自动配置类

2、在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)

@Configuration(proxyBeanMethods = false)
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {

    private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();

    // 从容器中获取所有的WebMvcConfigurer
    @Autowired(required = false)
    public void setConfigurers(List<WebMvcConfigurer> configurers) {
        if (!CollectionUtils.isEmpty(configurers)) {
            this.configurers.addWebMvcConfigurers(configurers);
            // 一个参考实现:将所有的WebMvcConfigurer相关的配置都来一起调用;
                // @Override
                // public void addViewControllers(ViewControllerRegistry registry) {
                //     for (WebMvcConfigurer delegate : this.delegates) {
                //         delegate.addViewControllers(registry);
                //     }
                // }
        }
    }

3、容器中所有的WebMvcConfigurer都会一起起作用;

4、我们的配置类也会被调用

效果:SpringMVC的自动配置和我们的扩展配置都会起作用;

3、全面接管SpringMVC(慎用!!!);

SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了

我们需要在配置类中添加@EnableWebMvc即可;

@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 浏览器发送 /zh 也来到success来到页面
        registry.addRedirectViewController("/zh", "success");
    }
}

原理:

为什么@EnableWebMvc自动配置就都失效了;

1、@EnableWebMvc的核心

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

2、

@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

3、

@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 {

4、@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;

5、导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能

5、如何修改SpringBoot的默认配置

模式:

1、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置,如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来。

2、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置

3、在SpringBoot中会有很多的xxxCustomizer帮助我们进行制定配置

6、RestfulCRUD

1、默认访问首页

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 浏览器发送 /zh 也来到success来到页面
        registry.addRedirectViewController("/zh", "success");
    }

    // 所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean // 将组件注册在容器中
    public WebMvcConfigurer webMvcConfigurerAdapter() {
        WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
            }
        };
        return webMvcConfigurer;
    }
}

2、国际化

1、编写国际化配置文件

2、使用ResourceBundleMessageSource管理国际化资源文件

3、(jsp页面)在页面使用fmt:message取出国际化内容

步骤:

1、编写国际化配置文件,抽取页面需要显示的国际化消息

image-20201015211354979.png

2、SpringBoot自动配置好了管理国际化资源文件的组件;

public class MessageSourceAutoConfiguration {

    private static final Resource[] NO_RESOURCES = {};

    @Bean
    @ConfigurationProperties(prefix = "spring.messages")
    public MessageSourceProperties messageSourceProperties() {
        return new MessageSourceProperties();
    }
    // 我们的配置文件可以直接放在类路径下叫做message.properties;

    @Bean
    public MessageSource messageSource(MessageSourceProperties properties) {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(properties.getBasename())) {
            // 设置国际化资源文件的基础名(去掉语言国家代码的基础名)
            messageSource.setBasenames(StringUtils
                    .commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
        }
        if (properties.getEncoding() != null) {
            messageSource.setDefaultEncoding(properties.getEncoding().name());
        }
        messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
        Duration cacheDuration = properties.getCacheDuration();
        if (cacheDuration != null) {
            messageSource.setCacheMillis(cacheDuration.toMillis());
        }
        messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
        messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
        return messageSource;
    }

3、去页面获取国际化的值:

image-20201015212840365.png

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="">
        <meta name="author" content="">
        <title>Signin Template for Bootstrap</title>
        <!-- Bootstrap core CSS -->
        <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
        <!-- Custom styles for this template -->
        <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
    </head>

    <body class="text-center">
        <form class="form-signin" action="dashboard.html">
            <img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
            <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
            <label class="sr-only" th:text="#{login.username}">Username</label>
            <input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
            <label class="sr-only" th:text="#{login.password}">Password</label>
            <input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
            <div class="checkbox mb-3">
                <label>
          <input type="checkbox" value="remember-me" > [[#{login.remember}]]
        </label>
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
            <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
            <a class="btn btn-sm">中文</a>
            <a class="btn btn-sm">English</a>
        </form>
    </body>
</html>

效果:根据浏览器语言设置的信息切换了国际化;

原理:

国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象)

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
    if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
        return new FixedLocaleResolver(this.mvcProperties.getLocale());
    }
    AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
    localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
    return localeResolver;
}
默认的就是根据请求头带来的区域信息获取locale进行国际化

4、点击链接切换国际化

/**
 * @author cai-xiansheng
 * @Description 我们可以在链接上携带区域信息
 * @create 2020-10-15 21:42
 */
public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = "";
        l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if (!StringUtils.isEmpty(l)) {
            String[] split = l.split("_");
            locale = new Locale(split[0], split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

@Bean
public LocaleResolver localeResolver() {
    return new MyLocaleResolver();
}

3、登录

开发期间模板引擎页面修改以后,要实时生效

1)、禁用模板引擎的缓存

# 禁用缓存
spring.thymeleaf.cache=false

2)、页面修改完成以后ctrl+f9:重新编译;

登录错误消息的显示

<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

4、拦截器进行登录检查

拦截器

/**
 * @author cai-xiansheng
 * @Description 登录检查,
 * @create 2020-10-15 22:53
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    // 目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginUser = request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            // 未登录,返回登录页面
            request.setAttribute("msg", "没有权限,请先登录!");
            request.getRequestDispatcher("/").forward(request, response);
            return false;
        } else {
            // 已登录
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

注册拦截器

// 所有的WebMvcConfigurerAdapter组件都会一起起作用
@Bean // 将组件注册在容器中
public WebMvcConfigurer webMvcConfigurerAdapter() {
    WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
        // 注册视图控制器
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("login");
            registry.addViewController("/index.html").setViewName("login");
            registry.addViewController("/main.html").setViewName("dashboard");
        }

        // 注册拦截器
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 静态资源: *.css, *.js
            // SpringBoot已经做好了静态资源映射
            registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html", "/", "/user/login", "/asserts/**", "/webjars/**");
        }
    };
    return webMvcConfigurer;
}

5、CRUD - 员工列表

实验要求:

1)、RestfulCRUD:CRUD满足Rest风格;

URI:/资源名称/资源标识

HTTP请求方式区分对资源CRUD操作

普通CRUD(URI来区分操作) RestfulCRUD
查询 getEmp emp—-GET
添加 addEmp?xxx emp—-POST
修改 updateEmp?id=xxx&xxx=xx emp/{id}—-PUT
删除 deleteEmp?id=1 emp/{id}—-DELETE

2)、试验的请求架构;

实验功能 请求URI 请求方式
查询所有员工 emps GET
查询某个员工(来到修改页面) emp/1 GET
来到添加页面 emp GET
添加员工 emp POST
来到修改页面(查出员工进行信息回显) emp/1 GET
修改员工 emp PUT
删除员工 emp/1 DELETE

3)、员工列表:

thymeleaf公共页面元素抽取

1、抽取公共片段
<div th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</div>

2、引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名

3、默认效果:
insert的功能片段放在div标签中
如果使用th:insert等属性进行引入,可以不用写~{};
[[~{}]];[(~{})]

三种引入公共片段的th属性:

th:insert:将公共片段整个插入到声明引入的元素中

th:replace:将声明引入的元素替换为公共片段

th:include:将被引入的片段的内容包含进这个标签

<footer th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</footer>

引入方式:
<body>
...
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
</body>

效果:
<body>
...
<div>
    <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
</div>
<footer>
&copy; 2011 The Good Thymes Virtual Grocery
</footer>
<div>
&copy; 2011 The Good Thymes Virtual Grocery
</div>
</body>

引入片段的时候传入参数:

<nav class="col-md-2 d-none d-md-block bg-light sidebar" id="sidebar">
    <div class="sidebar-sticky">
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link active"
                   th:class="${activeUri=='main.html'?'nav-link active':'nav-link'}"
                   href="#" th:href="@{/main.html}">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
                        <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                        <polyline points="9 22 9 12 15 12 15 22"></polyline>
                    </svg>
                    Dashboard <span class="sr-only">(current)</span>
                </a>
            </li>

<!--引入侧边栏;传入参数-->
<div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>

6、CRUD-员工添加

添加页面

<form>
    <div class="form-group">
        <label>LastName</label>
        <input type="text" class="form-control" placeholder="zhangsan">
    </div>
    <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" placeholder="zhangsan@atguigu.com">
    </div>
    <div class="form-group">
        <label>Gender</label><br/>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="gender"  value="1">
            <label class="form-check-label">男</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="gender"  value="0">
            <label class="form-check-label">女</label>
        </div>
    </div>
    <div class="form-group">
        <label>department</label>
        <select class="form-control">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
        </select>
    </div>
    <div class="form-group">
        <label>Birth</label>
        <input type="text" class="form-control" placeholder="zhangsan">
    </div>
    <button type="submit" class="btn btn-primary">添加</button>
</form>

提交的数据格式不对:生日:日期;

2020-10-15;2020/10/15;2020.10.15;

日期的格式化;SpringMVC将页面提交的值需要转换为制定的类型;

2020-10-15—-Date;类型转换,格式化;

默认日期是按照/的方式

7、CRUD-员工修改

修改添加二和一表单

<!--需要区分是员工修改还是添加;-->
<form th:action="@{/emp}" method="post">
    <!--发送put请求修改员工数据-->
    <!--
1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)
2、页面创建一个post表单
3、创建一个input项,name="_method";值就是我们指定的请求方式
-->
    <input type="hidden" name="_method" value="put" th:if="${emp!=null}"/>
    <input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}">
    <div class="form-group">
        <label>LastName</label>
        <input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${emp.lastName}">
    </div>
    <div class="form-group">
        <label>Email</label>
        <input name="email" type="email" class="form-control" placeholder="zhangsan@atguigu.com" th:value="${emp!=null}?${emp.email}">
    </div>
    <div class="form-group">
        <label>Gender</label><br/>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender==1}">
            <label class="form-check-label">男</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp!=null}?${emp.gender==0}">
            <label class="form-check-label">女</label>
        </div>
    </div>
    <div class="form-group">
        <label>department</label>
        <!--提交的是部门的id-->
        <select class="form-control" name="department.id">
            <option th:selected="${emp!=null}?${dept.id == emp.department.id}" th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option>
        </select>
    </div>
    <div class="form-group">
        <label>Birth</label>
        <input name="birth" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}">
    </div>
    <button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button>
</form>

8、CRUD-员工删除

<tr th:each="emp:${emps}">
    <td th:text="${emp.id}"></td>
    <td>[[${emp.lastName}]]</td>
    <td th:text="${emp.email}"></td>
    <td th:text="${emp.gender}==0?'女':'男'"></td>
    <td th:text="${emp.department.departmentName}"></td>
    <td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></td>
    <td>
        <a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
        <button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除</button>
    </td>
</tr>


<script>
    $(".deleteBtn").click(function(){
        //删除当前员工的
        $("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
        return false;
    });
</script>

7、错误处理机制

由于spring boot版本的改变,我们需要在properties文件中配置

server.error.include-exception=true
server.error.include-message=always

1、SpringBoot默认的错误处理机制

默认效果:

1、浏览器,返回一个默认的错误页面

image-20201016201732841.png

浏览器发送的请求头:

2、如果是其他客户端,默认响应一个json数据

{
    "timestamp": "2020-10-20T02:28:16.867+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "",
    "path": "/crud/aa"
}

image-20201020105102712

原理:

可以参照ErrorMvcAutoConfiguration;错误处理的自动配置;

给容器中添加了一下组件:

1、DefaultErrorAttributes;

    @Override
    @Deprecated
    public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = new LinkedHashMap<>();
        errorAttributes.put("timestamp", new Date());
        errorAttributes.put("path", request.path());
        Throwable error = getError(request);
        MergedAnnotation<ResponseStatus> responseStatusAnnotation = MergedAnnotations
                .from(error.getClass(), SearchStrategy.TYPE_HIERARCHY).get(ResponseStatus.class);
        HttpStatus errorStatus = determineHttpStatus(error, responseStatusAnnotation);
        errorAttributes.put("status", errorStatus.value());
        errorAttributes.put("error", errorStatus.getReasonPhrase());
        errorAttributes.put("message", determineMessage(error, responseStatusAnnotation));
        errorAttributes.put("requestId", request.exchange().getRequest().getId());
        handleException(errorAttributes, determineException(error), includeStackTrace);
        return errorAttributes;
    }
帮我们在页面共享信息

2、BasicErrorController:处理默认/error请求

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {

    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) // 产生html类型的数据;浏览器发送过来的请求来到这个方法处理
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        Map<String, Object> model = Collections
                .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());

        // 去哪个页面作为错误页面,包含页面地址和页面内容
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
        return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
    }
    @RequestMapping // 产生jspn数据,其他客户端来到这个方法处理
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        return new ResponseEntity<>(body, status);
    }

3、ErrorPageCustomizer:

    @Value("${error.path:/error}")
    private String path = "/error"; 系统出现错误以后来到error请求进行处理;(web.xml注册的错误页面规则)

4、DefaultErrorViewResolver:

@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
    ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);
    if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
        modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
    }
    return modelAndView;
}

private ModelAndView resolve(String viewName, Map<String, Object> model) {
    // 默认springBoot可以去找到一个页面?error/404
    String errorViewName = "error/" + viewName;
    // 模板引擎可以接这个页面地址就用模板引擎解析
    TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
            this.applicationContext);
    if (provider != null) {
        // 模板引擎可用的情况下返回errorViewName指定的视图地址
        return new ModelAndView(errorViewName, model);
    }
    // 模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html
    return resolveResource(errorViewName, model);
}

步骤:

一旦系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error请求,就会被BasicErrorController处理;

响应页面:去哪个页面是由DefalutErrorViewResolver解析得到的

    protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status,
            Map<String, Object> model) {
        // 所有的ErrorViewResolverResolver
        for (ErrorViewResolver resolver : this.errorViewResolvers) {
            ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
            if (modelAndView != null) {
                return modelAndView;
            }
        }
        return null;
    }

2、如果定制错误响应:

1、如何定制错误页面;

  • 有模板引擎的情况下;error/状态码;【将错误页面命名为错误状态码.html放在模板引擎文件夹里面的error文件夹下】,发生此状态吗的错误就会来到对应的页面。
    • 我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html);
    • 页面能获取的信息:
      • timestamp:时间戳
      • status:
      • error:
      • exception:
      • message:异常消息
      • errors:JSR303数据校验的错误都在这里
  • 没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找(但是动态数据就解析不了);
  • 以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面;

2、如何定制错误的json数据;

  • 自定义异常处理 & 返回定制json数据
@ControllerAdvice
public class MyExceptionHandler {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map<String, Object> handlerException(Exception e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", "user.notexist");
        map.put("message", e.getMessage());
        return map;
    }
}
// 没有自适应效果...
  • 转发到/error进行自适应响应效果
@ExceptionHandler(Exception.class)
public String handlerException(Exception e, HttpServletRequest request) {
    // 传入我们自己的错误状态码,4xx,5xx,否则就不会进入错误定制页面的解析流程,
    /**
     * Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
     */
    request.setAttribute("javax.servlet.error.status_code", 500);
    Map<String, Object> map = new HashMap<>();
    map.put("code", "user.notexist");
    map.put("message", e.getMessage());
    // 转发到、/error
    return "forward:/error";
}

3、将我们的定制数据携带出去

出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttrubutes得到的(是AbstractErrorController(ErrorController)规定的方法);

1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中,

2、页面上能用的数据,或者是json返回能员工的数据都是通过errorAttruibutes.getErrorAttributes得到;

容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;

自定义ErrorAttributes

@Component
public class MyErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options);
        errorAttributes.put("company", "zh");
        return errorAttributes;
    }
}

最终的效果:响应是自适应的,可以通过指定ErrorAttributes改变需要返回的内容。

{
    "timestamp": "2020-10-20T12:23:36.848+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "exception": "com.zh.springboot.exception.UserNotExistException",
    "message": "用户不存在",
    "path": "/crud/hello",
    "company": "zh",
    "ext": {
        "code": "user.notexist",
        "message": "用户不存在"
    }
}

可以通过request进行数据传输(也就是进行公共的数据传递)

8、配置嵌入式Servlet容器

SpringBoot默认使用Tomcat作为嵌入式Servlet容器

image-20201020203506121.png

1、如何定制和修改Servlet容器的相关配置

1、修改和server有关的配置(ServerProperties【EmbeddedServletContainerCustomizer】)

server.port=8081
server.servlet.context-path=/crud

server.tomcat.uri-encoding=UTF-8

# 通用的Servlet容器设置
server.xxx
# Tomcat的设置
server.tomcat.xxx

2、编写一个EmbeddedServletContainerCustomizer(嵌入式的Servlet容器的定制器);来修改Servlet容器的配置

@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> webServerFactoryWebServerFactoryCustomizer() {
    return new WebServerFactoryCustomizer<TomcatServletWebServerFactory>() {
        // 定制嵌入式的Servlet容器相关的规则
        @Override
        public void customize(TomcatServletWebServerFactory factory) {
            factory.setPort(8083);
        }
    };
}

2、注册Servlet三大组件【Servlet、Filter、Listener】

由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。

注册三大组件用以下方式

ServletRegistrationBean

    // 注册三大组件
    @Bean
    public ServletRegistrationBean myServlet() {
        ServletRegistrationBean<MyServlet> myServletServletRegistrationBean = new ServletRegistrationBean<>(new MyServlet(), "/myServlet");
        return myServletServletRegistrationBean;
    }

FilterRegistrationBean

@Bean
public FilterRegistrationBean myFilter() {
    FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
    filterFilterRegistrationBean.setFilter(new MyFilter());
    filterFilterRegistrationBean.setUrlPatterns(Arrays.asList("/hello", "/myServlet"));
    return filterFilterRegistrationBean;
}

ServletListenerRegistrationBean

@Bean
public ServletListenerRegistrationBean myListener() {
    return new ServletListenerRegistrationBean(new MyListener());
}

SpringBoot帮我们自动注册SpringMVC的时候,自动的注册SpringMVC的前段控制器;DispatcherServlet;DispatcherServletAutoConfiguration中:

@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name =
DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public ServletRegistrationBean dispatcherServletRegistration(
    DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean registration = new ServletRegistrationBean(
        dispatcherServlet, this.serverProperties.getServletMapping());
        //默认拦截: / 所有请求;包静态资源,但是不拦截jsp请求; /*会拦截jsp
        //可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径
        registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
        registration.setLoadOnStartup(
        this.webMvcProperties.getServlet().getLoadOnStartup());
        if (this.multipartConfig != null) {
            registration.setMultipartConfig(this.multipartConfig);
        } 
        return registration;
}

3、替换为其他嵌入式Servlet容器

image-20201021134049709.png

默认支持:

Tomcat(默认使用)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    引入web模块默认就是使用嵌入式的tomcat作为servlet容器
</dependency>

jetty(长连接)

<!--引入web模块-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>

<!--引入其他Servlet容器-->
<dependency>
    <artifactId>spring-boot-starter-jetty</artifactId>
    <groupId>org.springframework.boot</groupId>
</dependency>

undertow(不支持jsp)

<!-- 引入web模块 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>

<!--引入其他Servlet容器-->
<dependency>
    <artifactId>spring-boot-starter-undertow</artifactId>
    <groupId>org.springframework.boot</groupId>
</dependency>

4、嵌入式Servlet容器自动配置原理

EmbeddedWebServerFactoryCustomizerAutoConfiguration:嵌入式的Servlet容器自动配置

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@EnableConfigurationProperties(ServerProperties.class)
public class EmbeddedWebServerFactoryCustomizerAutoConfiguration {

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass({ Tomcat.class, UpgradeProtocol.class }) // 判断当前是否引入了tomcat依赖
    public static class TomcatWebServerFactoryCustomizerConfiguration {
    // 创建嵌入式的Servlet容器
        @Bean
        public TomcatWebServerFactoryCustomizer tomcatWebServerFactoryCustomizer(Environment environment,
                ServerProperties serverProperties) {
            return new TomcatWebServerFactoryCustomizer(environment, serverProperties);
        }

    }

自动配置步骤:

  • Spring Boot根据导入的依赖情况,给容器中添加相应的EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactory】
  • 容器中某个组件要创建对象机会惊动后置处理器:EmbeddedServletContainerCustomizerBeanPostProcessor;只要是嵌入式的容器工厂,后置处理器就工作。
  • 后置处理器,从容器中获取所有的EmbeddedServletContainerCustomizer,调用定制器的定制方法

5、嵌入式Servlet容器启动原理

什么时候创建嵌入式的Servlet容器工厂化,什么时候获取嵌入式的Servlet容器并启动Tomcat;获取嵌入式的Servlet容器工厂。

1、SpringBoot应用启动运行run方法

2、refreshContext(context); Spring Boot刷新IOC容器【创建IOC容器对象,并初始化容器,创建容器中的每一个组件】;如果是web应用创建AnnotationConfigEmbeddedWebApplicationContext,否则:AnnotationConfigApplication

3、refresh(context)刷新好刚才的ioc容器

    @Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Prepare the bean factory for use in this context.
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);

                // Initialize message source for this context.
                initMessageSource();

                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();

                // Initialize other special beans in specific context subclasses.
                onRefresh();

                // Check for listener beans and register them.
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                finishRefresh();
            }

            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }

4、onRefresh():web的ioc容器重写了onRefresh方法

5、webioc容器会创建嵌入式的Servlet容器:createEmbeddedServletContainer()

6、获取嵌入式的Servlet工厂: EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory(); 从ioc容器中获取EmbeddedServletContainerFactory组件;TomcatEmbeddedServletContainerFactory创建对象,容器处理器一看是这个对象,就获取所有的地址器来定制Servlet容器的相关配置。

7、使用容器工厂获取嵌入式的Servlet容器:this.embeddedServletContainer = containerFactory.getEmbeddedServletConatiner(getSelfInitializer());

8、嵌入式的Servlet容器创建对象并启动Servlet容器;

先启动嵌入式的Servlet容器,再将ioc容器中剩下的没有创建的对象获取出来

ioc容器启动的时候创建嵌入式的Servlet容器

9、使用外置的Servlet容器

嵌入式Servlet容器:应用打成可执行的jar

    优点:简单、便携;

    缺点:默认不支持jsp、优化定制比较复杂(使用定制器【ServerProperties、自定义EmbeddedServletContainerCustomizer】,自己编写嵌入式Servlet容器的创建工厂【EmbeddedServletContinerFactory】);

外置的Servlet容器,外面安装tomcat—应用war包的方式打包

步骤

1、必须创建一个war项目:(利用idea创建好目录结构)

2、将嵌入式的Tomcat指定为provided

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

3、必须编写一个SpringBootServletInitalizer的子类,并调用Configure方法

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        // 传入SpringBoot应用程序的主程序
        return application.sources(Springboot04WebJspApplication.class);
    }

}

4、启动服务器就可以使用

原理

jar包:执行SpringBoot主类的main方法,启动ioc容器,创建嵌入式的Servlet容器;

war包:启动服务器,服务器启动SpringBoot应用【SpringBootServletInitializer】,启动ioc容器

规则:

  • 服务器启动(web应用启动)会创建当前web应用里面每一个jar包里面ServletContainerInitializer实例:
  • ServletContainerInitializer的实现会放在jar包的META-INF/services文件夹下,有一个名为javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInializer的实现类的全类名
  • 还可以使用@HandlesTypes,在应用启动的时候加载我们感兴趣的类。

流程:

  • 启动Tomcat
  • org\springframework\spring-web\4.3.14.RELEASE\spring-web-4.3.14.RELEASE.jar!\METAINF\services\javax.servlet.ServletContainerInitializer: Spring的web模块里面有这个文件: org.springframework.web.SpringServletContainerInitializer
  • SpringServletContainerInitializer将@HandlesTypes(WebApplicationInitializer.class)标注的所有这个类型的类都传入到onStartup方法的Set>;为这些WebAPplicationInitializer类型的类创建实例
  • 每一个WebApplicationInitializer都调用自己的onStartup;
  • image-20201021153536041.png
  • 相当于我们的SpringBootServletInitializer的类会被创建对象,并执行onStartup方法
  • SpringBootServletInitializer实例执行onStartup的时候会createRootApplicationContext;创建容器

    protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
      // 创建SpringApplicationBuilder
      SpringApplicationBuilder builder = createSpringApplicationBuilder();
      builder.main(getClass());
      ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
      if (parent != null) {
          this.logger.info("Root context already created (using as parent).");
          servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
          builder.initializers(new ParentContextApplicationContextInitializer(parent));
      }
      builder.initializers(new ServletContextApplicationContextInitializer(servletContext));
      builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class);
      // 调用configure方法,子类重写了这个方法,将SpringBoot的主程序闯入了进来
      builder = configure(builder);
      builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext));
      // 使用builder创建一个Spring应用
      SpringApplication application = builder.build();
      if (application.getAllSources().isEmpty()
              && MergedAnnotations.from(getClass(), SearchStrategy.TYPE_HIERARCHY).isPresent(Configuration.class)) {
          application.addPrimarySources(Collections.singleton(getClass()));
      }
      Assert.state(!application.getAllSources().isEmpty(),
              "No SpringApplication sources have been defined. Either override the "
                      + "configure method or add an @Configuration annotation");
      // Ensure error pages are registered
      if (this.registerErrorPageFilter) {
          application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class));
      }
      application.setRegisterShutdownHook(false);
      // 启动Spring应用
      return run(application);
    }
    
  • Spring的应用就启动并且创建ioc容器

    public ConfigurableApplicationContext run(String... args) {
      StopWatch stopWatch = new StopWatch();
      stopWatch.start();
      ConfigurableApplicationContext context = null;
      Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
      configureHeadlessProperty();
      SpringApplicationRunListeners listeners = getRunListeners(args);
      listeners.starting();
      try {
          ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
          ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
          configureIgnoreBeanInfo(environment);
          Banner printedBanner = printBanner(environment);
          context = createApplicationContext();
          exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                  new Class[] { ConfigurableApplicationContext.class }, context);
          prepareContext(context, environment, listeners, applicationArguments, printedBanner);
          // 刷新ioc容器
          refreshContext(context);
          afterRefresh(context, applicationArguments);
          stopWatch.stop();
          if (this.logStartupInfo) {
              new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
          }
          listeners.started(context);
          callRunners(context, applicationArguments);
      }
      catch (Throwable ex) {
          handleRunFailure(context, ex, exceptionReporters, listeners);
          throw new IllegalStateException(ex);
      }
    
      try {
          listeners.running(context);
      }
      catch (Throwable ex) {
          handleRunFailure(context, ex, exceptionReporters, null);
          throw new IllegalStateException(ex);
      }
      return context;
    }
    

启动Servlet容器,再启动SpringBoot应用