Spring Boot系列第四篇:Spring Boot与Web开发

一、简介

1.使用SpringBoot

创建一个springboot应用,选择我们需要的模块

SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来

自己编写业务代码

自动配置原理:

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

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

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

可以设置和静态资源有关的参数,缓存时间

@ConfigurationProperties(
    prefix = "spring.resources",
    ignoreUnknownFields = false
)
public class ResourceProperties implements ResourceLoaderAware {

第一种所有/webjars/** 都去classpath:/META-INF/resources/webjars/找资源,webjars:以jar包的方式引入静态资源, 以前都是在webapp下引入静态资源webjars

public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Integer cachePeriod = this.resourceProperties.getCachePeriod();
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(cachePeriod));
                }

                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));
                }

            }
 }

在这里插入图片描述
静态资源访问路径:http://localhost:8082/webjars/jquery/3.3.1/jquery.js

        <!--引入jquery-webjar-->在访问的时候只需要写webjars下面的资源名称即可
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

第二种/** 访问当前项目的任何资源
“classpath:/META-INF/resources/”, (从java包下或者resource路径下都是类路径)
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/”,
“/”当前项目的根路径

localhost:8080/abc 去静态资源文件下去找abc
http://localhost:8082/asserts/js/Chart.min.js
1
第三种欢迎页,静态资源文件下的所有index.html页面,被 / * * 映射
localhost:8080/ 找index页面
配置欢迎页映射

        private WelcomePageHandlerMapping(Resource welcomePage, String staticPathPattern) {
            if (welcomePage != null && "/**".equals(staticPathPattern)) {
                logger.info("Adding welcome page: " + welcomePage);
                ParameterizableViewController controller = new ParameterizableViewController();
                controller.setViewName("forward:index.html");
                this.setRootHandler(controller);
                this.setOrder(0);
            }

        }

第四种:配置喜欢的图标

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

        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(-2147483647);
                mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
                return mapping;
            }

            @Bean
            public ResourceHttpRequestHandler faviconRequestHandler() {
                ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
                requestHandler.setLocations(this.resourceProperties.getFaviconLocations());
                return requestHandler;
            }
        }

自定义静态资源文件
spring.resources.static-locations=classpath:/hello/、classpath:/abc/
以前默认的静态资源会访问不到

3.SpringBoot_web开发-引入thymeleaf

模板引擎:jsp、thymeleaf、freemarker
mo
thymeleaf语法简单,功能更强大

1.引入thymeleaf

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
       <!-- 切换版本-->
         <properties>
	        <thymeleaf.version>3.0.2.RELEASE </thymeleaf.version>
	        <!--布局功能的支持程序 thymeleaf3主程序 layout2以上版本-->
	        <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
        </properties>

2.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就能帮我们自动渲染了

使用:
1.导入名称空间在HTML页面

< 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>
</head>
<body>
    <h3>成功页</h3>
    <!--th:text 将div里的文本内容设置为-->
    <div th:text="${hello}"></div>
</body>
</html>

3.语法规则
th:text 改变当前元素里的文本内容
th:任意HTML属性,替换原生属性的值
表达式
thymeleaf

二、springmvc自动配置原理

springboot

1.mvc配置原理

以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何
渲染(转发?重定向?))

ContentNegotiatingViewResolver:组合所有的视图解析器的;
如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来;

Support for serving static resources, including support for WebJars (see below).静态资源文件夹路
径,webjars
Static index.html support. 静态首页访问
Custom Favicon support (see 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的所有自动场景;
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration
(interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type
WebMvcConfigurerAdapter , but without @EnableWebMvc . If you wish to provide custom instances of
RequestMappingHandlerMapping , RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver
you can declare a WebMvcRegistrationsAdapter instance providing such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with
@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注解
既保留了所有的自动配置,也能用我们扩展的配置

package com.ming.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 使用WebMvcConfigurerAdapter可以来扩展springmvc的功能
 */
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    //视图映射
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //super.addViewControllers(registry);
        //浏览器发送http://localhost:8082/ming请求来到success页面
        registry.addViewController("/ming").setViewName("success");
    }
}

原理:
1.WebMvcAutoConfiguration是spingmvc的自动配置类
2.在做其他自动配置时会导入@Import(EnableWebMvcConfiguration.class)

public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
	//从容器中获取所有的WebMvcConfigurer
	@Autowired(required = false)
    public void setConfigurers(List<WebMvcConfigurer> configurers) {
        if (!CollectionUtils.isEmpty(configurers)) {
            this.configurers.addWebMvcConfigurers(configurers);
        }
	//一个参考实现,将所有的WebMvcConfigurer的相关配置都来一起调用
	//public void addViewControllers(ViewControllerRegistry registry) {
       // Iterator var2 = this.delegates.iterator();
       // while(var2.hasNext()) {
          //  WebMvcConfigurer delegate = (WebMvcConfigurer)var2.next();
          //  delegate.addViewControllers(registry);
      //  }
   // }
    }
}

3.容器中所有的WebMvcConfigurer都会一起起作用
4.我们的配置类也会被调用
效果:springmvc的自动配置和我们的扩展配置都会起作用

全面接管springmvc
springboot对springmvc的自动配置我们不需要了,所有的都是我们自己配置,所有的springmvc自动配置都会失效,比如访问首页404,我们需要在配置类中添加@EnableWebMvc

为什么加了个@EnableWebMvc自动配置会失效?

@EnableWebMvc的核心

package org.springframework.web.servlet.config.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@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组件导入进来了(@Import({DelegatingWebMvcConfiguration.class})继承了WebMvcConfigurationSupport )导入进来了

导入的WebMvcConfigurationSupport 只是springmvc的基本功能

3.如何修改SpringBoot的默认配置

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

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

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

三、SpringBoot web开发

1.默认访问首页

    /**
     * 首页 模板引擎
     * @return
     */
    @RequestMapping({"/","/index.html"})
    public String index(){
        return "index";
    }

适用模板引擎


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

2.国际化

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

步骤:
1.编写国际化配置文件,抽取页面需要显示的国际化消息
在这里插入图片描述
2.SpringBoot自动配置好了管理国际化资源文件的组件

@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
//我们的配置文件可以直接放在类路径下叫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;
	}

3.去页面获取国际化的值
新版idea在New projects setting
在这里插入图片描述

<!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">© 20172018</p>            
<a class="btn btn‐sm">中文</a>            
<a class="btn btn‐sm">English</a>            
</form>        
</body>    
</html>

效果:根据浏览器语言设置的信息切换了国际化(浏览器中设置语音)
原理:
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象)

ean        
@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.点击链接切换国际化

/**
 * 点击链接切换国际化,可以在链接上携带区域信息
 *
 */
public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(l)){
            //zh-CN
            String[] s = l.split("_");
            locale = new Locale(s[0],s[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

/**
 * 使用WebMvcConfigurerAdapter可以来扩展springmvc的功能
 */
@Configuration
//@EnableWebMvc 不要接管springmvc
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    //国际化解析器组件
    @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>
package com.ming.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {

    //@RequestMapping(value = "/user/login",method = RequestMethod.POST)
    @PostMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String, Object> map,
                        HttpSession session) {
        if (!StringUtils.isEmpty(username) && password.equals("123456")) {
            //登陆成功,为了防止表单重复提交,可以重定向到主页
            //配置registry.addViewController("/main.html").setViewName("dashboard");
            session.setAttribute("loginUser",username);
            return "redirect:/main.html";
        } else {
            //登陆失败,来到登录页面显示错误消息
            map.put("msg", "用户名密码错误");
            return "login";
        }

    }
}

4、拦截器

package com.ming.component;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if(user == null){
            //未登录,返回登录页面
            request.setAttribute("msg","没有权限先登录");
            request.getRequestDispatcher("/index.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 {

    }
}

注册拦截器

package com.ming.config;

import com.ming.component.LoginHandlerInterceptor;
import com.ming.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 使用WebMvcConfigurerAdapter可以来扩展springmvc的功能
 */
@Configuration
//@EnableWebMvc 不要接管springmvc
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    //视图映射
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //super.addViewControllers(registry);
        //浏览器发送http://localhost:8082/ming请求来到success页面
        registry.addViewController("/ming").setViewName("success");
    }

    //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @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,spingboot已经做好了资源映射了,不用处理静态资源
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/index.html","/","/user/login");
            }

        };
        return adapter;
    }


    //国际化解析器组件
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }
}

5、RESTFUL-CRUD员工列表

实验要求:
1.RestFulCRUD:crud要满足rest风格

URl:资源名称+资源标识 Http请求的方式区分对资源CRUD的操作

普通CRUD(url区分操作)RestFulCRUD
查询getEmpemp–GET
添加addEmp?xxxemp–POST
修改updateEmp?id=1emp/{id}–PUT
删除deleteEmp?id=1emp/{id}–DELETE

2.实验的请求架构

请求URl请求方式
查询所有员工empsGET
查询某个员工emp/{id}GET
来到添加页面empGET
添加员工empPOST
来到修改页面(查出员工进行回显)emp/{id}GET
修改员工emp/{id}PUT
删除员工emp/{id}DELETE

3.员工列表
thymeleaf公共页面元素抽取
1、抽取公共片段

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

抽取页面顶部

	<body>
		<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
			<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
			<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
			<ul class="navbar-nav px-3">
				<li class="nav-item text-nowrap">
					<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
				</li>
			</ul>
		</nav>

2、引入公共片段

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

在列表页先引入模板引擎

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

删除以前的顶部页面 引入公共页面的顶部 topbar

3、默认效果:
insert的公共片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{}
行内写法可以加上:

[[~{}]]

[(~{})]

三种引入公共片段的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>

引入顶部

		<!--引入抽取的topbar-->
		<!--模板名:会使用thymeleaf的前后缀配置规则进行解析-->
		<div th:replace="dashboard :: topbar"></div>

引入的侧边栏

	<!--引入公共的侧边栏 模板名::id 引入<nav class="col-md-2 d-none d-md-block bg-light sidebar" id="sidebar">-->
	<div th:replace="dashboard :: #sidebar"></div>

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

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

4.员工添加

//来到员工添加页面
    @GetMapping("/emp")
    public String toAddPage(Model model){
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        return "emp/add";
    }

    //springmvc请求的参数和入参对象进行一一绑定 要求请求参数的名字和Javabean入参对象里面的属性名是一样的
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        employeeDao.save(employee);

        //redirect:表示重定向到一个地址 /代表当前 项目路径
        //forward:转发到一个地址
        return "redirect:/emps";
    }

提交的数据格式不对:生日的日期
2017-12-12 2017/12/12 2017.12.12
日期的格式化 SpringMVC将页面提交的值需要转换为指定的类型
2017-12-12—Date; 类型转换,格式化
默认日期是按照 / 的方式
配置文件日期格式化

#日期格式化
spring.mvc.date-format=yyyy-MM-dd

5.CRUD-员工修改
点击编辑按钮来到修改页面

<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
<!--需要区分是员工修改还是添加;-->
<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}">
    //来到员工修改页面,先查出当前页面员工
    @GetMapping("/emp/{id}")
    public String toEdit(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        //修改和添加一个页面
        return "emp/add";
    }

    @PutMapping("/emp")
    public String updateEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

8.CRUD-员工删除

<div class="container-fluid">
			<div class="row">
			<!--引入公共的侧边栏 模板名::id 引入<nav class="col-md-2 d-none d-md-block bg-light sidebar" id="sidebar">-->
			<div th:replace="commons/bar :: #sidebar(activeUri='emps')"></div>
				<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
					<h2><a class="btn btn-sm btn-success" href="emp" th:href="@{/emp}">员工添加</a></h2>
					<div class="table-responsive">
						<table class="table table-striped table-sm">
							<thead>
								<tr>
									<th>#</th>
									<th>lastName</th>
									<th>email</th>
									<th>gender</th>
									<th>department</th>
									<th>birth</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
							<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>

							</tbody>
						</table>
					</div>
				</main>
				<!--删除-->
				<form id="deleteEmpForm"  method="post">
					<input type="hidden" name="_method" value="delete"/>
				</form>
			</div>
		</div>
		//js
		<script>
			$(".deleteBtn").click(function(){
				//删除当前员工的
				$("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
				return false;
			});
		</script>
    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

6、错误处理机制

一、springboot默认的错误处理机制

默认效果:
错误处理机制
浏览器发送请求的请求头
浏览器发送请求的请求头
如果是其他客户端比如IOS,默认响应一个json数据
2
2
原理
可以参照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:系统出现错误后生效

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

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处理
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;
	}

第二种响应json数据:

二、如何定制错误响应:

1.如何定制错误的页面

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

我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html)
页面能获取的信息有:
timestamp:时间戳 status:状态码 error:错误提示 exception:异常对象 message:异常消息 errors:JSR303数据校验的错误都在这里

没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找,注意:静态资源文件下不能动态获取信息(比如status)

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

2.如何定制错误的JOSN数据

1.自定义异常处理&返回定制json数据

/**
 * 自定义异常
 */
public class UserNotExistException extends RuntimeException  {

    public UserNotExistException() {
        super("用户不存在");
    }
 }
package com.ming.controller;

import com.ming.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义异常处理器
 */
@ControllerAdvice
public class MyExceptionHandler {

    /**
     * 要处理的异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(UserNotExistException.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;
    }
}
//没有自适应效果 

2、没有自适应效果 ,解决转发forward:/error 页面

package com.ming.controller;

import com.ming.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义异常处理器
 */
@ControllerAdvice
public class MyExceptionHandler {

    /**
     * 要处理的异常
     *
     * bug:浏览器客户端访问返回的都是json数据,应该浏览器访问返回页面,客户端访问返回json
     * @return
     */
//    @ResponseBody
//    @ExceptionHandler(UserNotExistException.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;
//    }

    /**
     * 自适应返回json或html页面
     * @param e
     * @return
     */
    @ExceptionHandler(UserNotExistException.class)
    public String handlerException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制的错误页面
        //Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        //转发到error
        return  "forward:/error";
    }

}

//转发到源码的error
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
}

3、将我们的定制数据携带出去
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法)
1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中
2、页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到

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

errorAttributes.getErrorAttributes获取数据如下

	protected Map<String, Object> getErrorAttributes(HttpServletRequest request,
			boolean includeStackTrace) {
		RequestAttributes requestAttributes = new ServletRequestAttributes(request);
		return this.errorAttributes.getErrorAttributes(requestAttributes,
				includeStackTrace);
	}

自定义ErrorAttributes

package com.ming.component;

import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;

import java.util.Map;

/**
 * 自定义返回错误的数据
 * 源码DefaultErrorAttributes.getErrorAttributes()
 */
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
    //返回值的map就是页面和json能获取的所有字段
    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
        map.put("company","ming");//公司标识
        //我们的异常处理器携带的数据
        Map<String, Object>  ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);//0代表从reuqset域中获取
        map.put("ext",ext);
        return map;
    }
}

自定义异常

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

exception

7、配置嵌入式Servlet容器

SpringBoot默认使用Tomcat作为嵌入式的Servlet容器(Tomcat)
Tomcat
问题?
1、如何定制和修改Servlet容器的相关配置

修改和server有关的配置(ServerProperties【也是EmbeddedServletContainerCustomizer】)
application.properties文件中修改

server.port=8081
server.context‐path=/crud
server.tomcat.uri‐encoding=UTF‐8
//通用的Servlet容器设置
server.xxx
//Tomcat的设置
server.tomcat.xxx

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

    @Bean
    public EmbeddedServletContainerCustomizer myEmbeddedServletContainerCustomizer(){
        return new EmbeddedServletContainerCustomizer() {
            //定制嵌入式的servlet容器相关的规则
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                //container.setPort(8091);
            }
        };
    }

2、springboot 能不能支持其他的servlet容器

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

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

注册三大组件用以下方式
ServletRegistrationBean

package com.ming.config;

import com.ming.servlet.MyServlet;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 服务器有关的配置
 */
@Configuration
public class MyServerConfig{


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

}

自定义的servlet

package com.ming.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义servlet,要注册servlet要用springboot提供的ServletRegistrationBean
 */
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");
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}

浏览器访问http://localhost:8085/crud/myServlet 页面效果输出 Hello MyServlet

FilterRegistrationBean
自定义MyFilte

package com.ming.filter;

import org.apache.catalina.servlet4preview.http.HttpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;

import javax.servlet.*;
import java.io.IOException;

/**
 * 自定义filter要注册servlet要用springboot提供的FilterRegistrationBean
 */
public class MyFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //过滤请求
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("MyFilter Process...");
        //放行请求
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

package com.ming.config;

import com.ming.filter.MyFilter;
import com.ming.servlet.MyServlet;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;


/**
 * 服务器有关的配置
 */
@Configuration
public class MyServerConfig{


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

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

}

浏览器访问http://localhost:8085/crud/myServlet或者/hello请求,控制台输出MyFilter Process...
ServletListenerRegistrationBean
自定义的ServletContextListener

package com.ming.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * 自定义listener要用springboot提供的ServletListenerRegistrationBean
 * listener有很多主要监听servlet启动和销毁的Listener
 */
public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("contextInitialized初始化servlet...web应用启动");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println(".contextDestroyed销毁...关闭web应用以后,当前web项目销毁");

    }
}

ServletListenerRegistrationBean

package com.ming.config;

import com.ming.filter.MyFilter;
import com.ming.listener.MyListener;
import com.ming.servlet.MyServlet;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;


/**
 * 服务器有关的配置
 */
@Configuration
public class MyServerConfig{


    //注册servlet三大组件
    @Bean
    public ServletRegistrationBean myServlet(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
        registrationBean.setLoadOnStartup(1);//启动顺序
        return  registrationBean;
    }

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

    //注册Listener
    @Bean
    public ServletListenerRegistrationBean myListener(){
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean<MyListener>(new MyListener());
        return  servletListenerRegistrationBean;
    }

    //配置嵌入式的servlet容器
    @Bean
    public EmbeddedServletContainerCustomizer myEmbeddedServletContainerCustomizer(){
        return new EmbeddedServletContainerCustomizer() {
            //定制嵌入式的servlet容器相关的规则
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                //container.setPort(8091);
            }
        };
    }
}

效果:项目启动的时候控制台会打印contextInitialized初始化servlet...web应用启动、项目关闭的时候点Exit图标控制台打印contextDestroyed销毁...关闭web应用以后,当前web项目销毁

springboot帮我们自动配置springmvc的时候,自动注册了springmvc的前端控制器DispatcherServlet
给容器中注册了DispatcherServlet也是通过ServletRegistrationBean 注册的

		@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());
			//默认拦截的路径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;
		}

4、替换为其他嵌入式Servlet容器
Jetty(长连接)、Undertow(不支持jsp、高并发性能好)
默认支持
在这里插入图片描述
Tomcat(默认使用)
默认使用的原因是web模块引入了Tomcat

        <!--引入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>

Jetty
先排除Exclude默认的Tomcat

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

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

5、嵌入式的servlet容器自动配置原理

EmbeddedServletContainerAutoConfiguration :嵌入式的servlet容器自动配置

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@ConditionalOnWebApplication
@Import(BeanPostProcessorsRegistrar.class)//导入BeanPostProcessorsRegistrar后置处理器的注册器:spring注解版有
//作用就是给容器中导入一些组件EmbeddedServletContainerCustomizerBeanPostProcessor导入了后置处理器
//后置器的处理作用:就是在bean初始化前后执行前置或者后置的一些逻辑,刚创建完对象还没有给属性赋值,进行初始化工作
public class EmbeddedServletContainerAutoConfiguration {
	@Configuration
	@ConditionalOnClass({ Servlet.class, Tomcat.class })//判断当前是否引入了Tomcat
	@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)//判断当前容器中没有用户自己定义EmbeddedServletContainerFactory嵌入式的servlet容器工厂,作用:创建嵌入式的servlet容器
	public static class EmbeddedTomcat {

		@Bean
		public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
			return new TomcatEmbeddedServletContainerFactory();
		}
		
	/**
	 * Nested configuration if Jetty is being used.
	 */
	@Configuration
	@ConditionalOnClass({ Servlet.class, Server.class, Loader.class,
			WebAppContext.class })
	@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
	public static class EmbeddedJetty {

		@Bean
		public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
			return new JettyEmbeddedServletContainerFactory();
		}

	}

	/**
	 * Nested configuration if Undertow is being used.
	 */
	@Configuration
	@ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class })
	@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
	public static class EmbeddedUndertow {

		@Bean
		public UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory() {
			return new UndertowEmbeddedServletContainerFactory();
		}

	}

	}

}

EmbeddedServletContainerFactory(嵌入式的servlet容器工厂)

public interface EmbeddedServletContainerFactory {
	//获取嵌入式的servlet容器
    EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... var1);
}

servlet容器工厂

EmbeddedServletContainer 嵌入式的servlet容器
servlet容器
以嵌入式的TomcatEmbeddedServletContainerFactory容器工厂为例:

    public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) {
        Tomcat tomcat = new Tomcat();//创建一个Tomcat
        //配置Tomcat基本环境
        File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat");
        tomcat.setBaseDir(baseDir.getAbsolutePath());
        Connector connector = new Connector(this.protocol);//连接器
        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);
        //将配置好的Tomcat传进去,返回一个嵌入式的servlet容器,并且启动Tomcat容器
        return this.getTomcatEmbeddedServletContainer(tomcat);
    }

我们对嵌入式的容器配置修改是怎么生效的?
修改有两种方式:
修改配置文件ServerProperties
修改嵌入式的servlet容器定制器EmbeddedServletContainerCustomizer

EmbeddedServletContainerCustomizer:定制器帮我们修改了servlet容器的一些配置?比如端口号

怎么修改的原理?

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@ConditionalOnWebApplication
@Import(BeanPostProcessorsRegistrar.class)//导入BeanPostProcessorsRegistrar后置处理器的注册器:spring注解版有
//作用就是给容器中导入一些组件EmbeddedServletContainerCustomizerBeanPostProcessor导入了后置处理器
//后置器的处理作用:就是在bean初始化前后执行前置或者后置的一些逻辑,刚创建完对象还没有给属性赋值,进行初始化工作
public class EmbeddedServletContainerAutoConfiguration {

容器中导入了EmbeddedServletContainerCustomizerBeanPostProcessor

//初始化之前
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    //如果当前初始化的是一个ConfigurableEmbeddedServletContainer类型的组件就调用下面这个方法
        if (bean instanceof ConfigurableEmbeddedServletContainer) {
            this.postProcessBeforeInitialization((ConfigurableEmbeddedServletContainer)bean);
        }

        return bean;
    }
	//
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    private void postProcessBeforeInitialization(ConfigurableEmbeddedServletContainer bean) {
        Iterator var2 = this.getCustomizers().iterator();
		//获取所有的定制器,调用每一个定制器的customizer 方法来给servlet容器属性进行赋值,比如端口号,访问路径
        while(var2.hasNext()) {
            EmbeddedServletContainerCustomizer customizer = (EmbeddedServletContainerCustomizer)var2.next();
            customizer.customize(bean);
        }

    }

    private Collection<EmbeddedServletContainerCustomizer> getCustomizers() {
        if (this.customizers == null) {
        //beanFactory从IOC容器中按照类型获取所有EmbeddedServletContainerCustomizer这个类型的组件
       	//如果想要定制servlet容器,给容器中添加一个这个EmbeddedServletContainerCustomizer类型的组件
            this.customizers = new ArrayList(this.beanFactory.getBeansOfType(EmbeddedServletContainerCustomizer.class, false, false).values());
            Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE);
            this.customizers = Collections.unmodifiableList(this.customizers);
        }

        return this.customizers;
    }

ServerProperties也是定制器

步骤:
1、springboot根据导入的依赖情况给容器中添加相应的嵌入式容器工厂(TomcatEmbeddedServletContainerFactory
2、容器中添加了组件,容器中某个组件要创建对象就会惊动后置处理器(EmbeddedServletContainerCustomizerBeanPostProcessor)只要是嵌入式的servlet容器工厂,后置处理器就会工作
3、后置处理器从容器中获取所有的EmbeddedServletContainerCustomizer嵌入式servlet容器定制器,调用定制器的定制方法

6、嵌入式Servlet容器启动原理
什么时候创建嵌入式servlet容器工厂?什么时候获取嵌入式的servlet容器并启动Tomcat

获取嵌入式的servlet容器工厂:
1.springboot应用启动运行run方法
2.refreshContext(context);springboot刷新IOC容器【创建IOC对象并初始化容器,创建容器中的每一个组件】。如果是web应用就会创建
AnnotationConfigEmbeddedWebApplicationContext否则就会创建AnnotationConfigApplicationContext
3、refresh(context);刷新刚才创建好的IOC容器

  public void refresh() throws BeansException, IllegalStateException {
        synchronized(this.startupShutdownMonitor) {
            this.prepareRefresh();
            ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
            this.prepareBeanFactory(beanFactory);

            try {
                this.postProcessBeanFactory(beanFactory);
                this.invokeBeanFactoryPostProcessors(beanFactory);
                this.registerBeanPostProcessors(beanFactory);
                this.initMessageSource();
                this.initApplicationEventMulticaster();
                this.onRefresh();
                this.registerListeners();
                this.finishBeanFactoryInitialization(beanFactory);
                this.finishRefresh();
            } catch (BeansException var9) {
                if (this.logger.isWarnEnabled()) {
                    this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
                }

                this.destroyBeans();
                this.cancelRefresh(var9);
                throw var9;
            } finally {
                this.resetCommonCaches();
            }

        }
    }

4、this.onRefresh();web的IOC容器重写了onRefresh方法
5、web ioc 容器会创建嵌入式的servlet容器createEmbeddedServletContainer();
6、获取嵌入式servlet容器工厂EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
从ioc容器中获取EmbeddedServletContainerFactory组件,TomcatEmbeddedServletContainerFactory 创建对象,后置处理器一看是这个对象,就获取所有的定制器来先定制servlet容器的相关配置
7、使用容器工厂获取嵌入式的servlet容器this.embeddedServletContainer = containerFactory.getEmbeddedServletContainer(getSelfInitializer())
8、嵌入式的servlet容器创建对象并启动servlet容器,先启动嵌入式的servlet容器,然后再将IOC容器中没有创建出的对象获取出来

IOC容器启动创建嵌入式的Servlet容器

8、使用外置的Servlet容器

嵌入式servlet容器:应用打成可执行的jar
优点:简单、便携
缺点:默认不支持jsp、优化和定制比较复杂(使用定制器serverProperties、自定义EmbeddedServletContainerCustomizer、自己编写嵌入式Servlet容器的创建工厂EmbeddedServletContainerFactory)

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

步骤:
1、必须创建一个war项目
生成webapp、点击idea的project structure项目结构
创建webapp目录
web
创建web.xml文件、文件是在项目的src\main\webapp\WEB-INF\web.xml
web.xml

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

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

3、必须编写一个SpringBootServletInitializer的子类,并调用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容器

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

流程
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>;为这些WebApplicationInitializer类型的类创建实例;

4、每一个WebApplicationInitializer都调用自己的onStartup;
在这里插入图片描述

5、相当于我们的SpringBootServletInitializer的类会被创建对象,并执行onStartup方法
6、SpringBootServletInitializer实例执行onStartup的时候会createRootApplicationContext;创建容器

protected WebApplicationContext createRootApplicationContext(
      ServletContext servletContext) {
    //1、创建SpringApplicationBuilder
   SpringApplicationBuilder builder = createSpringApplicationBuilder();
   StandardServletEnvironment environment = new StandardServletEnvironment();
   environment.initPropertySources(servletContext, null);
   builder.environment(environment);
   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(AnnotationConfigEmbeddedWebApplicationContext.class);
   
    //调用configure方法,子类重写了这个方法,将SpringBoot的主程序类传入了进来
   builder = configure(builder);
   
    //使用builder创建一个Spring应用
   SpringApplication application = builder.build();
   if (application.getSources().isEmpty() && AnnotationUtils
         .findAnnotation(getClass(), Configuration.class) != null) {
      application.getSources().add(getClass());
   }
   Assert.state(!application.getSources().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.getSources().add(ErrorPageFilterConfiguration.class);
   }
    //启动Spring应用
 }

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

	public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		FailureAnalyzers analyzers = null;
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(
					args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners,
					applicationArguments);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			analyzers = new FailureAnalyzers(context);
			prepareContext(context, environment, listeners, applicationArguments,
					printedBanner);
					//刷新IOC容器
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			listeners.finished(context, null);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass)
						.logStarted(getApplicationLog(), stopWatch);
			}
			return context;
		}
		catch (Throwable ex) {
			handleRunFailure(context, listeners, analyzers, ex);
			throw new IllegalStateException(ex);
		}
	}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值