4 - Spring Boot与Web开发

一、简介

使用SpringBoot:

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

自动配置原理?

这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?

xxxxAutoConfiguration:帮我们给容器中自动配置组件。
xxxxProperties:配置类来封装配置文件的内容。
在autoconfigure包下的web中

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

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
//可以设置和静态资源有关的参数,缓存时间等
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
        return;
    }
    Integer cachePeriod = this.resourceProperties.getCachePeriod();
    if (!registry.hasMappingForPattern("/webjars/**")) {
        customizeResourceHandlerRegistration(
          	registry.addResourceHandler("/webjars/**")
          		    .addResourceLocations(
            			"classpath:/META-INF/resources/webjars/")
          		    .setCachePeriod(cachePeriod));
    }
    String staticPathPattern = this.mvcProperties.getStaticPathPattern();
      //静态资源文件夹映射
      if (!registry.hasMappingForPattern(staticPathPattern)) {
        	customizeResourceHandlerRegistration(
            	registry.addResourceHandler(staticPathPattern)
            		    .addResourceLocations(
              				this.resourceProperties.getStaticLocations())
             			.setCachePeriod(cachePeriod));
    }
}
//配置欢迎页映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(
    ResourceProperties resourceProperties) {
    return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
                                       this.mvcProperties.getStaticPathPattern());
}
//配置喜欢的图标
@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
public static class FaviconConfiguration {
    private final ResourceProperties resourceProperties;
    public FaviconConfiguration(ResourceProperties resourceProperties) {
      	this.resourceProperties = resourceProperties;
    }
    @Bean
    public SimpleUrlHandlerMapping faviconHandlerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
        //所有  **/favicon.ico 
        mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
                                                   faviconRequestHandler()));
        return mapping;
    }
    @Bean
    public ResourceHttpRequestHandler faviconRequestHandler() {
        ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
        requestHandler
          .setLocations(this.resourceProperties.getFaviconLocations());
        return requestHandler;
    }
}
  1. 所有/webjars/**,都去classpath:/META-INF/resources/webjars/路径下找资源。

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

    例如:引用jquery

    在访问的时候只需要写webjars下面资源的名称即可:localhost:8080/webjars/jquery/3.3.1/jquery.js

    <!--引入jquery-webjar-->
    <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/" 
    "/":当前项目的根路径
    

    例如:在static下有一个文件asserts/js/Chart.min.js

    在访问的时候:localhost:8080/asserts/js/Chart.min.js即可。

  3. 欢迎页:静态资源文件夹下的所有index.html页面;被"/**"映射

    localhost:8080/ 默认找当前文件下的index页面

  4. 所有的 **/favicon.ico都是在静态资源文件下找

三、模板引擎

1、分类:JSP、Velocity、Freemarker、Thymeleaf
2、SpringBoot推荐的Thymeleaf。
3、Thymeleaf优点:语法更简单,功能更强大。
4、使用Thymeleaf:
  • 引入thymeleaf:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    切换thymeleaf版本,springboot2.2.2中用的是spring5,所以thymeleaf要带上spring5
    <properties>
        <thymeleaf-spring5.version>3.0.9.RELEASE</thymeleaf-spring5.version>
        <!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
        <!-- thymeleaf2   layout1-->
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
    </properties>
    
    要是版本冲突还可以
    <properties>
        <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
        <!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
        <!-- thymeleaf2   layout1-->
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
    </properties>
    
  • 使用thymeleaf

    @ConfigurationProperties(prefix = "spring.thymeleaf")
    public class ThymeleafProperties {
    
    	private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
    
    	private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
    
    	public static final String DEFAULT_PREFIX = "classpath:/templates/";
    
    	public static final String DEFAULT_SUFFIX = ".html";
    

    只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

  • 导入thymeleaf的名称空间(在html页面)

    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    
5、使用thymeleaf语法
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>success</title>
</head>
<body>
    <h1>成功</h1>
    <!--th:text 将div里面的文本内容设置为 -->
    <div th:text="${hello}">
        这是欢迎信息
    </div>
</body>
</html>
  1. 语法规则

    • th:text----->改变当前元素里面的文本内容。

      th:html的任意属性---->来替换原生属性的值。

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZBqoDSvM-1588428738229)(/images/md/2018-02-04_123955.png)]

  • 表达式:

    Simple expressions:(表达式语法)
        一、Variable Expressions: ${...}:获取变量值,类似OGNL。
        		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}:从session获取值
                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: _ 
    
6、thymeleaf抽取模板使用
  1. 模板页面

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <!--定义成模板,传入参数,每个页面的title不一样--> 
    <head th:fragment="head(title)">
        <meta charset="utf-8">
        <!--手机端支持-->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
      	<!--将title内容替换成传过来的参数-->
        <title th:replace="${title}"></title>
        <!--css-->
        <link rel="stylesheet" th:href="@{semanticui/semantic.min.css}">
        <link rel="stylesheet" th:href="@{css/typo.css}" />
        <link rel="stylesheet" th:href="@{css/animate.css}" />
        <link rel="stylesheet" th:href="@{lib/prims/prism.css}" />
        <link rel="stylesheet" th:href="@{lib/tocbot/tocbot.css}" />
        <link rel="stylesheet" th:href="@{css/me.css}">
        <!--js-->
        <script type="text/javascript" th:src="@{js/jquery-3.4.1.min.js}"></script>
        <script type="text/javascript" th:src="@{semanticui/semantic.min.js}"></script>
        <script type="text/javascript" th:src="@{lib/prims/prism.js}"></script>
        <script type="text/javascript" th:src="@{lib/tocbot/tocbot.min.js}"></script>
        <script type="text/javascript" th:src="@{lib/qrcode/qrcode.min.js}"></script>
        <script type="text/javascript" th:src="@{lib/scroll/jquery.scrollTo.min.js}"></script>
        <script type="text/javascript" th:src="@{lib/waypoint/jquery.waypoints.min.js}"></script>
    </head>
    <body>
    
    </body>
    </html>
    
  2. 引用模板页面

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
      	<!--引用位置,就是替换那一块的内容-->
    	<head th:replace="fragments::head(~{::title})">
    		<meta charset="utf-8">
    		<!--手机端支持-->
    		<meta name="viewport" content="width=device-width, initial-scale=1.0">
    		<title>首页</title>
    	</head>
      	<body></body>
    </html>
    

四、SpringMVC自动配置

1、Spring MVC auto-configuration:SpringBoot自动配置好了SpringMVC

以下是SpringBoot对SpringMVC的默认配置:在WebMvcAutoConfiguration类中

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    • 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发或者重定向))
    • ContentNegotiatingViewResolver:组合所有的视图解析器的。
    • 如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来;
  • Support for serving static resources, including support for WebJars (see below).静态资源文件夹路径,

  • Static index.html support. 静态首页访问

  • Custom Favicon support (see below). favicon.ico

  • 自动注册了 of Converter, GenericConverter, Formatter beans。

    • Converter:转换器。 public String hello(User user):类型转换使用Converter

    • Formatter 格式化器。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或者@Component)

  • Automatic registration of MessageCodesResolver (see below).定义错误代码生成规则

  • Automatic use of a ConfigurableWebBindingInitializer bean (see below)

    我们可以配置一个ConfigurableWebBindingInitializer来替换默认的;(添加到容器)

    初始化WebDataBinder;
    请求数据=====JavaBean;
    

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

如果你想要保留Spring Boot对Spring MVC自动配置的功能,并且只是想要额外的添加一些功能(如:拦截器、格式化器、视图控制器等),你可以添加你自己的一个用@Configuration标注的配置类,这个配置类的类型是WebMvcConfigurerAdapter,不能标注@EnableWebMvc。如果您希望提供RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定义实例,您可以声明一个提供此类组件的WebMvcRegistrationsAdapter实例。

如果你想完全控制Spring MVC,你可以用@EnableWebMvc添加你自己的@Configuration注解。

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类型;继承自WebMvcConfigurerAdapter类,不能标注@EnableWebMvc

特点:既保留了所有的自动配置,也能用自己扩展的配置。

//新建一个包config,新建一个配置类MyConfig继承WebMvcConfigurerAdapter
//SpringBoot2.2.2版本中WebMvcConfigurationSupport替换WebMvcConfigurerAdapter
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //super.addViewControllers(registry);
        //作用:当浏览器发送/atguigu请求,就会来到success
        registry.addViewController("/atguigu").setViewName("success");
    }
}
//或者实现 WebMvcConfigurer 这个类,根据需求选择重写的方法
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

原理:

  • WebMvcAutoConfiguration是SpringMVC的自动配置类

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

    @Configuration
    	public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
          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);
                   //   }
                  }
              }
    	}
    
  • 容器中所有的WebMvcConfigurer都会一起起作用。

  • 我们的配置类也会被调用。

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

3、全面接管SpringMVC

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

只要在配置类上添加@EnableWebMvc 即可

//新建一个包config,新建一个配置类MyConfig继承WebMvcConfigurerAdapter
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //super.addViewControllers(registry);
        //作用:当浏览器发送/atguigu请求,就会来到success
        registry.addViewController("/atguigu").setViewName("success");
    }
}

原理:

为什么添加@EnableWebMvc,springmvc的自动配置就失效了

  • @EnableWebMvc的核心

    @Import({DelegatingWebMvcConfiguration.class})
    public @interface EnableWebMvc {
    }
    
    @Configuration
    public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
    
    @Configuration
    @ConditionalOnWebApplication
    @ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
    		WebMvcConfigurerAdapter.class })
    //容器中没有这个组件的时候,这个自动配置类才生效
    @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
    @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
    @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
    		ValidationAutoConfiguration.class })
    public class WebMvcAutoConfiguration {
    
  • @EnableWebMvc将WebMvcConfigurationSupport组件导入进来

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

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

1、三种配置模式:
  • SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean或者@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(如:ViewResolver)将用户配置的和自己默认的组合起来;
  • 在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
  • 在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置

六、RestfulCRUD

1、默认访问首页
//springboot1.5.9版本
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean//将组件注册到容器中
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter=new WebMvcConfigurerAdapter(){
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/login.html").setViewName("login");
            }
        };
        return adapter;
    }
}
//springboot2.2.2版本
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/login.html").setViewName("login");
    }
}
2、国际化

之前的做法

  • 编写国际化配置文件
  • 使用ResourceBundleMessageSource管理国际化资源文件
  • 在页面使用fmt:message取出国际化内容

使用SpringBoot实现国际化步骤:

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

    • 在resources文件夹下新建一个文件夹i18n,在i18n中新建一个国际化配置文件(具体页面.properties)

    • 命名规则:对应要国际化页面的名称_ 语言 _国籍.properties

    • 再新建一个中文国际化文件名称为:具体页面名_zh_CN.properties

    • 再新建一个英文国际化文件名称为:具体页面名_en_US.properties

    • 点击Resource Bundle进入编辑模式

      login.btn=登陆~
      login.password=密码~
      login.remember=记住我~
      login.tip=请登陆~
      login.username=用户名~
      
      login.btn=Sign in
      login.password=Password
      login.remember=Remember me
      login.tip=Please sign in
      login.username=Username
      
  • SpringBoot自动配置好了管理国际化资源文件的组件,在MessageSourceAutoConfiguration类下

    @ConfigurationProperties(prefix = "spring.messages")
    public class MessageSourceAutoConfiguration {
        /**
    	 * Comma-separated list of basenames (essentially a fully-qualified classpath
    	 * location), each following the ResourceBundle convention with relaxed support for
    	 * slash based locations. If it doesn't contain a package qualifier (such as
    	 * "org.mypackage"), it will be resolved from the classpath root.
    	 */
    	private String basename = "messages";  
        //我们的配置文件可以直接放在类路径下叫messages.properties;
        
        @Bean
    	public MessageSource messageSource() {
    		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    		if (StringUtils.hasText(this.basename)) {
                //设置国际化资源文件的基础名(去掉语言国家代码的)
    			messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
    					StringUtils.trimAllWhitespace(this.basename)));
    		}
    		if (this.encoding != null) {
    			messageSource.setDefaultEncoding(this.encoding.name());
    		}
    		messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
    		messageSource.setCacheSeconds(this.cacheSeconds);
    		messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
    		return messageSource;
    	}
    
  • 在application.properties或者application.yml文件下将国际化配置文件注入到springboot中

    #包名i18n+基本名login
    spring.messages.basename=i18n.login
    
  • 在html页面上获取国际化的值

    <!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  rel="stylesheet" th:href="@{'/webjars/bootstrap/4.0.0/css/bootstrap.css'}">
    		<!-- Custom styles for this template -->
    		<link  rel="stylesheet" th:href="@{'/assert/css/signin.css'}">
    	</head>
    	<body class="text-center">
    		<form class="form-signin" action="dashboard.html">
    			<img class="mb-4" src="assert/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" required="" autofocus="">
    			<label class="sr-only" th:text="#{login.password}">Password</label>
    			<input type="password" class="form-control" placeholder="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() ==org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) 	  {
          	return new FixedLocaleResolver(this.mvcProperties.getLocale());
        } else {
            AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
            localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
            return localeResolver;
        }
    }
    //默认的就是根据请求头带来的区域信息获取Locale进行国际化
    
  • 点击链接切换国际化

    //1、新建一个包component,新建一个类MyLocalResolver,实现LocaleResolver接口
    /**
     * 可以在链接上携带区域信息
     */
    public class MyLocalResolver implements LocaleResolver {
        //解析区域信息
        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            //获取请求参数的值
            String l = request.getParameter("l");
            //链接若是没有带区域信息,就使用默认的
            Locale locale=Locale.getDefault();
            //判断不为空就将链接携带的区域信息给Locale对象
            if(!StringUtils.isEmpty(l)){
                String[] s = l.split("_");
                locale=new Locale(s[0],s[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    
        }
    }
    //2、在MyConfig配置类中将国际化配置类注入到容器中
    @Bean//将组件注册到容器中
    public LocaleResolver localeResolver(){
      	return new MyLocalResolver();
    }
    //3、修改html文件中的超链接
    <a class="btn btn-sm" href="#" th:href="@{/login.html(l='zh_CN')}">中文</a>
    <a class="btn btn-sm" href="#" th:href="@{/login.html(l='en_US')}">English</a>
    
3、登录

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

  • 禁用模板引擎的缓存

    # 禁用缓存
    spring.thymeleaf.cache=false
    
  • 页面修改完以后ctrl+f9,重新编译一下

  • 登录错误消息的显示

    <p style="color:red" th:text="${error}" th:if="${not #strings.isEmpty(error)}"></p>
    
  • 控制器

    @Component
    @RequestMapping("/user")
    public class LoginController {
    
        //@GetMapping:get请求
        //@DeleteMapping:delete请求
        //@PutMapping:put请求
        //@RequestMapping(value = "user/login",method = RequestMethod.POST)
      	//@PathVariable:获取路径变量
        @PostMapping(value = "/login")
        public String login(@RequestParam("username") String username,
                            @RequestParam("password") String password,
                            Map<String,Object> map){
            if (!StringUtils.isEmpty(username) && password.equals("123456")){
                //登录成功,为防止重复提交表单,使用重定向
                return "redirect:/main.html";
            }else{
                map.put("error","用户名或者密码错误");
                return "login";
            }
        }
    }
    
4、拦截器进行登录检查
  • 在component下新建一个LoginHandlerInterceptor类实现HandlerInterceptor接口

    public class LoginHandlerInterceptor implements HandlerInterceptor {
        //目标方法执行之前
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            Object user = request.getSession().getAttribute("user");
            //判断user是否为空
            if(user==null){
                //未登录,返回登陆页面
                request.setAttribute("error","没有权限,请先登录");
                request.getRequestDispatcher("/login.html").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 {
    
        }
    }
    
  • 注册拦截器:在myConfig类中重写addInterceptors 方法

    	//注册拦截器
    	//addPathPatterns:表示拦截的请求
    	//excludePathPatterns:表示不拦截的请求
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //springboot已经做好了静态资源的映射,拦截器不处理静态资源
            registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**").excludePathPatterns("/login.html","/","/user/login");
        }
    

5、CRUD-员工列表

  • RestfulCRUD:CRUD满足Rest风格。

  • URI: /资源名称/资源标识 HTTP请求方式区分对资源CRUD操作

    普通CRUD(uri来区分操作)RestfulCRUD
    查询getEmpemp-----GET
    添加addEmp?xxxemp-----POST
    修改updateEmp?id=xxx&xxx=xxemp/id=1-----PUT
    删除deleteEmp?id=1emp/id=1----DELETE
  • thymeleaf公共页面元素抽取

    抽取公共片段方式一:th:fragment
        <div th:fragment="copy">
            &copy; 2011 The Good Thymes Virtual Grocery
        </div>
    抽取公共片段方式二:定义元素选择器
        <div id="copy">
            &copy; 2011 The Good Thymes Virtual Grocery
        </div>
    
    2、引入公共片段的两种方式:
    	模板名会使用thymeleaf的前后缀配置规则
    		~{templatename::fragmentname}:模板名::片段名
    		<div th:insert="~{footer :: copy}"></div>
       		~{templatename::selector}:模板名::选择器
    		<div th:insert="~{footer :: #copy}"></div>
    
    3、默认效果:
    insert的公共片段在div标签中
    如果使用th:insert等属性进行引入,可以不用写~{},直接<div th:insert="footer :: copy"></div>即可
    行内写法可以加上:[[~{}]];[(~{})];
    
    • 三种引入公共片段的th:属性

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

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

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

      <footer th:fragment="copy">
      &copy; 2011 The Good Thymes Virtual Grocery
      </footer>
      
      引入方式
      <div th:insert="footer :: copy"></div>
      <div th:replace="footer :: copy"></div>
      <div th:include="footer :: copy"></div>
      
      效果
      <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>
      
  • 在抽取公共片段的时候可以定义参数

    <a class="nav-link" href="#" th:href="@{/emps}"
                               th:class="${activeUri=='emps'?'nav-link active':'nav-link'}">
    
  • 在引入公共片段的时候传入参数,在片段名后加:(参数名=‘ 值 ’)

    <div th:replace="commons/com::#left_select(activeUri='emps')"></div>
    
5、日期格式化
  • 提交的数据格式:生日:日期;2017-12-12;2017/12/12;2017.12.12;

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

    2017-12-12—Date; 类型转换,格式化;

    默认日期是按照/的方式;

  • 自定义日期格式:在配置文件中设置

    #日期格式化
    spring.mvc.date-format=yyyy-MM-dd HH:mm
    
6、put方式请求
<!--需要区分是员工修改还是添加;-->
<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}"/>
7、员工删除

通过自定义属性绑定值th:attr=""

<button th:attr="del_uri=@{/emp/}+${emp.id}" class="">删除</button>
<script>
    $(".deleteBtn").click(function(){
        //删除当前员工的
        $("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
        return false;
    });
</script>

七、错误处理机制

1、springboot默认错误处理机制

默认效果

  • 浏览器,返回一个默认的错误页面,报错404。

    浏览器发送的请求头

    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
    Accept-Encoding: gzip, deflate, br
    Accept-Language: zh-CN,zh;q=0.9
    Cache-Control: max-age=0
    Connection: keep-alive
    
  • 如果是其他客户端,默认响应一个json数据

    {
        "timestamp": "2020-01-01T08:14:42.583+0000",
        "status": 404,
        "error": "Not Found",
        "message": "No message available",
        "path": "/restful/4"
    }
    
  • 原理:可以参照ErrorMvcAutoConfiguration;错误处理的自动配置;

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

    1、DefaultErrorAttributes

    帮我们在页面共享信息;
    @Override
    	public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
    			boolean includeStackTrace) {
    		Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
    		errorAttributes.put("timestamp", new Date());
    		addStatus(errorAttributes, requestAttributes);
    		addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);
    		addPath(errorAttributes, requestAttributes);
    		return errorAttributes;
    	}
    

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

    @Controller
    @RequestMapping("${server.error.path:${error.path:/error}}")
    public class BasicErrorController extends AbstractErrorController {
        
        @RequestMapping(produces = "text/html")//产生html类型的数据;浏览器发送的请求来到这个方法处理
    	public ModelAndView errorHtml(HttpServletRequest request,
    			HttpServletResponse response) {
    		HttpStatus status = getStatus(request);
    		Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
    				request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
    		response.setStatus(status.value());
            
            //去哪个页面作为错误页面;包含页面地址和页面内容
    		ModelAndView modelAndView = resolveErrorView(request, response, status, model);
    		return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
    	}
    
    	@RequestMapping
    	@ResponseBody    //产生json数据,其他客户端来到这个方法处理;
    	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    		Map<String, Object> body = getErrorAttributes(request,
    				isIncludeStackTrace(request, MediaType.ALL));
    		HttpStatus status = getStatus(request);
    		return new ResponseEntity<Map<String, Object>>(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), 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处理;

    • 响应页面,去哪个页面是由DefaultErrorViewResolver解析得到的。

      protected ModelAndView resolveErrorView(HttpServletRequest request,
            HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
          //所有的ErrorViewResolver得到ModelAndView
         for (ErrorViewResolver resolver : this.errorViewResolvers) {
            ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
            if (modelAndView != null) {
               return modelAndView;
            }
         }
         return null;
      }
      
2、如何错误响应
  • 如何定制错误页面

    1、有模板引擎的情况下;error/状态码; 【将错误页面命名为:错误状态码.html 放在模板引擎文件夹(templates)里面的 error文件夹下】,发生此状态码的错误就会来到对应的页面;

    2、我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html);

    ​ 页面能获取的信息:

    ​ timestamp:时间戳

    ​ status:状态码

    ​ error:错误提示

    ​ exception:异常对象

    ​ message:异常消息

    ​ errors:JSR303数据校验的错误都在这里

    3、没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找。

    4、以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面。

  • 如何定制错误的json数据

    1、自定义一个异常类,继承RuntimeException类

    public class UserNotExistException extends RuntimeException {
        public UserNotExistException() {
            super("用户不存在");
        }
    }
    

    2、自定义异常处理类&返回定制json数据,但是他没有自适应效果(浏览器访问返回html页面,其他客户端访问就返回json自符串的形式)

    //浏览器和其他客户端返回的都是json
    @ControllerAdvice
    public class MyExceptionHandler {
        @ResponseBody
        @ExceptionHandler(Exception.class)
        public Map<String,Object> handleException(Exception e){
            Map<String,Object> map=new HashMap<>();
            map.put("code","user.notexist");
            map.put("message",e.getMessage());
            return map;
        }
    }
    

    3、自定义一个控制器,测试自定义json错误信息

    @RestController
    public class HelloController {
        @RequestMapping("/hello")
        public String hello(@RequestParam String name){
            if (name.equals("aaa")){
                throw new UserNotExistException();
            }
            return "hello";
        }
    }
    

    3、转发到/error进行自适应响应效果处理 (浏览器访问返回html页面,其他客户端访问就返回json自符串的形式)

    @ControllerAdvice
    public class MyExceptionHandler {
        @ExceptionHandler(Exception.class)
        public String handleException(Exception e, HttpServletRequest request){
            Map<String,Object> map=new HashMap<>();
            //传入我们自己的状态码 4xx  5xx,否则就不会进入错误页面
            request.setAttribute("javax.servlet.error.status_code",500);
            map.put("code","user.notexist");
            map.put("message",e.getMessage());
            //转发到/error
            return "forward:/error";
        }
    }
    
  • 将我们的定制数据携带出去

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

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

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

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

    自定义一个类继承DefaultErrorAttributes ,在2.2版本中导入的是import org.springframework.boot.web.servlet.error.DefaultErrorAttributes这个包

    @Component
    public class MyErrorAttributes extends DefaultErrorAttributes {
        //返回的map就是页面和json能获取的所有字段
        @Override
        public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
            Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
            map.put("company","itan");
            //webRequest.getAttribute()的第二个参数取值有两个:0表示从request中和1表示从session中
            Map<String,Object> ext=(Map<String, Object>) webRequest.getAttribute("ext",0);
            //将异常处理器携带的数据加入到map中
            map.put("ext",ext);
            return map;
        }
    }
    

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

八、配置嵌入式Servlet容器

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

1、如何定制和修改Servlet容器的相关配置
  1. 修改和server有关的配置(ServerProperties【也是EmbeddedServletContainerCustomizer】)

    #修改访问端口
    server.port=8081
    #修改访问路径
    server.servlet.context-path=/restful
    #修改默认编码
    server.tomcat.uri-encoding=UTF-8
    
    //通用的Servlet容器设置
    server.xxx
    //Tomcat的设置
    server.tomcat.xxx
    
  2. 编写一个WebServerFactoryCustomizer:嵌入式的Servlet容器的定制器,来修改Servlet容器的配置

    @Bean//将他注入到SpringBoot容器中
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
      	return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
            //定制嵌入式的Servlet容器的相关规则
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
              factory.setPort(8003);
            }
      	};
    }
    
2、注册Servlet三大组件【Servlet、Filter、LIstener】

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

注册三大组件用以下方式

  1. 注册Servlet

    • 自定义一个Servlet,继承HttpServlet

      public class MyServlet extends HttpServlet {
          //处理get请求
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              doPost(req,resp);
          }
          //处理post请求
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              resp.getWriter().write("Hello MyServlet");
          }
      }
      
  • 注册Servlet

    @Bean//注入到容器中
    public ServletRegistrationBean myServlet(){
        //传入一个自己的servlet和映射路径
        ServletRegistrationBean registrationBean = 
                          new ServletRegistrationBean(new MyServlet(),"/myServlet");
        return registrationBean;
    }
    
  1. 注册Filter

    • 自定义一个Filter,实现Filter接口

      public class MyFilter implements Filter {
          @Override
          public void init(FilterConfig filterConfig) throws ServletException {}
          @Override
          public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
              System.out.println("filter执行了");
              //放行请求
              chain.doFilter(req,resp);
          }
          @Override
          public void destroy() {}
      }
      
  • 注册Filter

    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean filter = new FilterRegistrationBean();
        //传入一个自定义filter类
        filter.setFilter(new MyFilter());
        //设置拦截的请求
        filter.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
        return filter;
    }
    
  1. 注册Listener

    • 自定义一个Listener类,实现ServletContextListener接口

      public class MyListener implements ServletContextListener {
          @Override
          public void contextInitialized(ServletContextEvent sce) {
              System.out.println("contextInitialized...web应用启动了");
          }
          @Override
          public void contextDestroyed(ServletContextEvent sce) {
              System.out.println("contextDestroyed...当前web项目销毁");
          }
      }
      
  • 注册

    @Bean
    public ServletListenerRegistrationBean myListener(){
      	ServletListenerRegistrationBean<MyListener> listener = new 														ServletListenerRegistrationBean<>(new MyListener());
      return listener;
    }
    

    可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径

3、替换为其他嵌入式Servlet容器
  1. 默认Tomcat

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
       引入web模块默认就是使用嵌入式的Tomcat作为Servlet容器;
    </dependency>
    
  2. 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>
    
  3. Undertow

    <!-- 引入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容器自动配置的原理

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

@Configuration(proxyBeanMethods = false)
@AutoConfigureOrder(-2147483648)
@ConditionalOnClass({ServletRequest.class})
@ConditionalOnWebApplication( type = Type.SERVLET)
@EnableConfigurationProperties({ServerProperties.class})
@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})
public class ServletWebServerFactoryAutoConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({Servlet.class, Tomcat.class, UpgradeProtocol.class})
@ConditionalOnMissingBean(value = {ServletWebServerFactory.class},
                          search = SearchStrategy.CURRENT)
public static class EmbeddedTomcat {
  	public EmbeddedTomcat() {}
    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(ObjectProvider<TomcatConnectorCustomizer> connectorCustomizers, ObjectProvider<TomcatContextCustomizer> contextCustomizers, ObjectProvider<TomcatProtocolHandlerCustomizer<?>> protocolHandlerCustomizers) {
            TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
       factory.getTomcatConnectorCustomizers().addAll((Collection)connectorCustomizers.orderedStream().collect(Collectors.toList()));
            factory.getTomcatContextCustomizers().addAll((Collection)contextCustomizers.orderedStream().collect(Collectors.toList()));
            factory.getTomcatProtocolHandlerCustomizers().addAll((Collection)protocolHandlerCustomizers.orderedStream().collect(Collectors.toList()));
            return factory;
    }
}
public WebServer getWebServer(ServletContextInitializer... initializers) {
  if (this.disableMBeanRegistry) {
    Registry.disableRegistry();
  }
  Tomcat tomcat = new Tomcat();
  File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat");
  tomcat.setBaseDir(baseDir.getAbsolutePath());
  Connector connector = new Connector(this.protocol);
  connector.setThrowOnFailure(true);
  tomcat.getService().addConnector(connector);
  this.customizeConnector(connector);
  tomcat.setConnector(connector);
  tomcat.getHost().setAutoDeploy(false);
  this.configureEngine(tomcat.getEngine());
  Iterator var5 = this.additionalTomcatConnectors.iterator();
  while(var5.hasNext()) {
    Connector additionalConnector = (Connector)var5.next();
    tomcat.getService().addConnector(additionalConnector);
  }
  this.prepareContext(tomcat.getHost(), initializers);
  return this.getTomcatWebServer(tomcat);
}
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
  	return new TomcatWebServer(tomcat, this.getPort() >= 0);
}
public TomcatWebServer(Tomcat tomcat, boolean autoStart) {
    this.monitor = new Object();
    this.serviceConnectors = new HashMap();
    Assert.notNull(tomcat, "Tomcat Server must not be null");
    this.tomcat = tomcat;
    this.autoStart = autoStart;
    this.initialize();
}
private void initialize() throws WebServerException {
  logger.info("Tomcat initialized with port(s): " + this.getPortsDescription(false));
  Object var1 = this.monitor;
  synchronized(this.monitor) {
    try {
      this.addInstanceIdToEngineName();
      Context context = this.findContext();
      context.addLifecycleListener((event) -> {
        if (context.equals(event.getSource()) && "start".equals(event.getType())) {
          this.removeServiceConnectors();
        }
      });
      this.tomcat.start();
      this.rethrowDeferredStartupExceptions();
      try {
        ContextBindings.bindClassLoader(context, context.getNamingToken(), this.getClass().getClassLoader());
      } catch (NamingException var5) {
        ;
      }
      this.startDaemonAwaitThread();
    } catch (Exception var6) {
      this.stopSilently();
      this.destroySilently();
      throw new WebServerException("Unable to start embedded Tomcat", var6);
    }
  }
}

总结:

1、SpringBoot根据导入的依赖情况,容器中导入的ServletWebServerFactoryConfiguration配置类,给容器添加相应的TomcatServletWebServerFactory,通过TomcatServletWebServerFactory的getWebServer(),启动servelt容器。

2、容器中某个组件要创建对象就会惊动后置处理器;@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,

只要是嵌入式的Servlet容器工厂,后置处理器就工作,用与定制嵌入式容器的配置修改,

3、后置处理器,执行postProcessBeforeInitialization()方法,调用定制器的定制方法;

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

获取嵌入式的Servlet容器工厂:

  • SpringBoot应用启动运行run方法

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

  • refresh(context);刷新刚才创建好的ioc容器;

  • onRefresh(); web的ioc容器重写了onRefresh方法

  • webioc容器会创建嵌入式的Servlet容器;createEmbeddedServletContainer();

  • 获取嵌入式的Servlet容器工厂:

    EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();

    ​ 从ioc容器中获取EmbeddedServletContainerFactory 组件;TomcatEmbeddedServletContainerFactory创建对象,后置处理器一看是这个对象,就获取所有的定制器来先定制Servlet容器的相关配置;

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

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

6、使用外置的Servlet容器
1、嵌入式Servlet容器:应用打成可执行的jar
  • 优点:简单、便携;

  • 缺点:默认不支持JSP、优化定制比较复杂

2、外置的Servlet容器:外面安装Tomcat—应用是war包的方式打包
3、步骤
  • 必须创建一个war项目;(利用idea创建好目录结构)

  • 将嵌入式的Tomcat指定为provided

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-tomcat</artifactId>
       <scope>provided</scope>
    </dependency>
    
  • 必须编写一个SpringBootServletInitializer的子类,并调用configure方法

    public class ServletInitializer extends SpringBootServletInitializer {
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(SpringBoot04WebJspApplication.class);
        }
    }
    
  • 启动服务器就可以使用

4、原理

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

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

servlet规则:

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

  2. org\springframework\spring-web\4.3.14.RELEASE\spring-web-4.3.14.RELEASE.jar!\META-INF\services\javax.servlet.ServletContainerInitializer:

    Spring的web模块里面有这个文件:org.springframework.web.SpringServletContainerInitializer

  3. SpringServletContainerInitializer将@HandlesTypes(WebApplicationInitializer.class)标注的所有这个类型的类都传入到onStartup方法的Set<Class<?>>;为这些WebApplicationInitializer类型的类创建实例

  4. 每一个WebApplicationInitializer都调用自己的onStartup

  5. 相当于我们的SpringBootServletInitializer的类会被创建对象,并执行onStartup方法

  6. SpringBootServletInitializer实例执行onStartup的时候会createRootApplicationContext;创建容器

  7. Spring的应用就启动并且创建IOC容器

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot是一种基于Java的快速应用程序开发框架,旨在简化新Spring应用程序的创建和部署。它提供了自动配置、开箱即用的功能和简单的Maven配置,使您能够使用Spring框架来开发Web应用程序。 要使用Spring Boot开发Web应用程序,首先需要在pom.xml文件中添加spring-boot-starter-web依赖: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> ``` 然后,您可以创建一个Spring控制器来处理Web请求。例如,以下是一个简单的控制器,它响应'/hello'路径的GET请求: ``` @RestController public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; } } ``` 最后,您可以使用Spring Boot提供的内置Tomcat服务器在本地运行应用程序。只需在应用程序的main方法中添加@SpringBootApplication注解并调用SpringApplication.run方法即可启动应用程序: ``` @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 这就是使用Spring Boot开发Web应用程序的基本流程。希望这些信息对您有帮助。 ### 回答2: Spring Boot 是一个开源的Java开发框架,它可以帮助开发者快速构建基于Spring框架的应用程序。用Spring Boot开发Web应用非常方便。 首先,Spring Boot提供了自动配置功能,简化了应用程序的配置过程。通过使用注解和约定,Spring Boot能够自动配置应用程序所需的各种组件和依赖项,例如数据库连接、Web服务器等。这样开发人员不需要手动编写大量的配置代码,提高了开发效率。 其次,Spring Boot具有内嵌的Web服务器(如Tomcat、Jetty等)和Servlet容器。这意味着开发者无需部署额外的Web服务器,只需打包应用程序为可执行的JAR文件,即可直接运行。这样可以减少运维工作和服务器资源的消耗。 另外,Spring Boot还提供了丰富的开发工具和插件,如Spring Boot DevTools和Spring Boot Actuator等。这些工具可以帮助开发人员快速开发和调试应用程序,还可以监控和管理应用程序的各种指标和状态。 除此之外,Spring Boot还支持使用Spring MVC快速构建RESTful API,同时也能与其他框架如Thymeleaf、Freemarker、Velocity等进行无缝集成,方便实现前后端分离的开发模式。 总之,Spring Boot是一个强大而简化的开发框架,它使得Spring应用程序的开发更加快速、高效。无论是开发小型项目还是大型复杂项目,都可以选择使用Spring Boot开发Web应用。 ### 回答3: Spring Boot是一个用于简化Spring应用程序开发的框架。它提供了一个快速开发的环境,并且具有自动化的配置,减少了开发人员的工作量。在使用Spring Boot开发Web应用程序时,可以遵循以下步骤: 1. 配置pom.xml:在项目的pom.xml文件中,添加Spring Boot相关的依赖项。通常包括Spring WebSpring Data JPA、Spring Security等。 2. 创建Controller:使用注解方式创建Controller类,处理来自客户端的请求。通过@RestController注解,可以将Controller类中的处理方法的返回值直接作为响应体返回给客户端。 3. 创建Service:在Service类中,编写业务逻辑代码。可以使用注解@Service将类标记为Service组件,并且使用@Autowired注解注入其他的依赖。 4. 创建Repository:在Repository类中,编写数据库操作的代码。可以使用注解@Repository将类标记为Repository组件,并且使用Spring Data JPA提供的接口来实现对数据库的操作。 5. 定义实体类:根据业务需求,定义与数据库表对应的实体类。实体类中使用注解@Entity标记类为实体类,并且使用注解@Id标记主键字段。 6. 配置数据库连接:在application.properties文件中,配置数据库连接信息,包括数据库URL、用户名、密码等。 7. 运行应用程序:通过main方法启动Spring Boot应用程序。Spring Boot会自动创建并配置好相应的运行环境,并且根据配置的端口号监听客户端的请求。 8. 测试应用程序:使用工具如Postman发送HTTP请求,测试Controller中定义的接口。可以通过URL访问接口,并且根据请求的参数和响应的结果,验证应用程序的正确性。 通过上述步骤,使用Spring Boot开发Web应用程序能够快速简便地搭建一个可靠的系统。同时,Spring Boot还提供了自动化的配置和部署功能,让开发人员能够专注于业务逻辑的开发,而不需要关心复杂的配置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值