1.简介
使用SpringBoot
- 创建SpringBoot应用,选中我们需要的模块
- SpringBoot默认将这些场景配置好了,只需要在配置文件中指定少量的配置就可以运行
- 编写业务代码
自动配置原理:
这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?xxx
xxxxAutoConfiguration:帮我们给容器中自动配置组件;
xxxxProperties:配置类来封装配置文件的内容
2.SpringBoot对静态资源的映射规则
-
所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源
webjars:以jar包的方式引入静态资源;
访问方式:localhost:8080/webjars/jquery/3.3.1/jquery.js
引入jquery坐标依赖:<!‐‐引入jquery‐webjar‐‐>在访问的时候只需要写webjars下面资源的名称即可 <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
-
“/**” 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
- “classpath:/META‐INF/resources/”,
- “classpath:/resources/”,
- “classpath:/static/”,
- “classpath:/public/”
- “/”:当前项目的根路径
localhost:8080/abc === 去静态资源文件夹里面找abc
-
欢迎页(首页): 静态资源文件夹下的所有index.html页面;被"/**"映射
localhost:8080/ 找index页面 -
(网页图标):所有的 **/favicon.ico 都是在静态资源文件下找
3. 模板引擎
JSP、Velocity、Freemarker、Thymeleaf
SpringBoot推荐的Thymeleaf:语法更简单,功能更强大
-
引入thymeleaf
-
Thymeleaf使用
只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染使用:
(1)导入thymeleaf的名称空间
(2)使用thymeleaf语法
-
语法规则
(1)th:text;改变当前元素里面的文本内容th:任意html属性;来替换原生属性的值
(2)表达式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} 3)、内置的一些工具对象: #execInfo : information about the template being processed. #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax. #uris : methods for escaping parts of URLs/URIs #conversions : methods for executing the configured conversion service (if any). #dates : methods for java.util.Date objects: formatting, component extraction, etc. #calendars : analogous to #dates , but for java.util.Calendar objects. #numbers : methods for formatting numeric objects. #strings : methods for String objects: contains, startsWith, prepending/appending, etc. #objects : methods for objects in general. #bools : methods for boolean evaluation. #arrays : methods for arrays. #lists : methods for lists. #sets : methods for sets. #maps : methods for maps. #aggregates : methods for creating aggregates on arrays or collections. #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration). Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样; 补充:配合 th:object="${session.user}: <div th:object="${session.user}"> <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p> </div> Message Expressions: #{...}:获取国际化内容 Link URL Expressions: @{...}:定义URL; @{/order/process(execId=${execId},execType='FAST')} Fragment Expressions: ~{...}:片段引用表达式 <div th:insert="~{commons :: main}">...</div> Literals(字面量) Text literals: 'one text' , 'Another one!' ,… Number literals: 0 , 34 , 3.0 , 12.3 ,… Boolean literals: true , false Null literal: null Literal tokens: one , sometext , main ,… Text operations:(文本操作) String concatenation: + Literal substitutions: |The name is ${name}| Arithmetic operations:(数学运算) Binary operators: + , ‐ , * , / , % Minus sign (unary operator): Boolean operations:(布尔运算) Binary operators: and , or Boolean negation (unary operator): ! , not Comparisons and equality:(比较运算) Comparators: > , < , >= , <= ( gt , lt , ge , le ) Equality operators: == , != ( eq , ne ) Conditional operators:条件运算(三元运算符) If‐then: (if) ? (then) If‐then‐else: (if) ? (then) : (else) Default: (value) ?: (defaultvalue) Special tokens: No‐Operation: _
4.SpringMVC自动配置
-
Spring MVC auto-configuration
Spring Boot 自动配置好了SpringMVC
以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration)- Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
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
自己添加的格式化器转换器,我们只需要放在容器中即可
- 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来替换默认的;(添加到容器)
- Inclusion of
-
扩展SpringMVC
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc既保留了所有的自动配置,也能用我们扩展的配置
原理:
(1) WebMvcAutoConfiguration是SpringMVC的自动配置类
(2) 在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)
(3) 容器中所有的WebMvcConfigurer都会一起起作用
(4) 我们的配置类也会被调用效果:SpringMVC的自动配置和我们的扩展配置都会起作用;
-
全面接管SpringMVC
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了 我们需要在配置类中添加@EnableWebMvc即可
@EnableWebMvc自动配置失效原理:
(1) @EnableWebMvc的核心
(2)
(3)
(4) @EnableWebMvc将WebMvcConfigurationSupport组件导入进来(5) 导入的WebMvcConfigurationSupport只是SpringMVC基本的功能
5.如何修改PsringBoot的默认配置
模式:
- SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如 果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默 认的组合起来
- 在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
- 在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置
6. RestfulCRUD
6.1.默认访问首页
6.2. 国际化
-
编写国际化配置文件
-
使用ResourceBundleMessageSource管理国际化资源文件
-
在页面使用fmt:message取出国际化内容
步骤:
(1)编写国际化配置文件,抽取页面需要显示的国际化消息
(2)SpringBoot自动配置好了国际化资源管理文件的组件
(3)去页面获取国际化的值
首先将编码改为UTF-8解决
修改login.html页面
编写代码实现LocaleResolver接口的类:
添加到MVCconfig中:
效果:根据浏览器语言设置的信息切换了国际化
原理:国际化Locale(区域信息对象) ;LocaleResolver(获取区域信息对象)
(4)点击链接切换国际化
6.3.登录
- 禁用模板引擎的缓存
- 页面修改完成以后ctrl+f9:重修编译
登陆错误消息的显示
6.4. 拦截器进行登陆检查
拦截器
注册拦截器.
6.5.CRUD员工列表
实验要求:
-
ResftulCRUD:CRUD满足Rest风格
URI:/资源名称/资源标识/ HTTP请求方式区分对资源CRUD操作
-
实验的请求架构
-
员工列表
thmeleaf公共页面元素抽取
三种引入公共片段的th属性:-
th:insert:将公共片段整个插入到声明引入的元素中
-
th:将声明引入的元素替换为公共片段
-
th:将被引入的片段的内容包含进这个标签中
<footer th:fragment="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> © 2011 The Good Thymes Virtual Grocery </footer> </div> <footer> © 2011 The Good Thymes Virtual Grocery </footer> <div> © 2011 The Good Thymes Virtual Grocery </div>
引入片段时传入参数:
-
6.6. CRUD-员工添加
添加页面
6.7. CRUD -员工修改
-
修改添加二合一表单
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"> <!--需要区分是员工修改还是添加;--> <form th:action="@{/emp}" method="post"> <!--发送put请求修改员工数据--> <!-- 1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的) 2、页面创建一个post表单 3、创建一个input项,name="_method";值就是我们指定的请求方式 --> <input type="hidden" name="_method" value="put" th:if="${emp!=null}"/> <input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}"> <div class="form-group"> <label>LastName</label> <input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${emp.lastName}"> </div> <div class="form-group"> <label>Email</label> <input name="email" type="email" class="form-control" placeholder="zhangsan@atguigu.com" th:value="${emp!=null}?${emp.email}"> </div> <div class="form-group"> <label>Gender</label><br/> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender==1}"> <label class="form-check-label">男</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp!=null}?${emp.gender==0}"> <label class="form-check-label">女</label> </div> </div> <div class="form-group"> <label>department</label> <!--提交的是部门的id--> <select class="form-control" name="department.id"> <option th:selected="${emp!=null}?${dept.id == emp.department.id}" th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option> </select> </div> <div class="form-group"> <label>Birth</label> <input name="birth" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"> </div> <button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button> </form>
-
修改提交的数据格式:生日:日期;
2017-12-12;2017/12/12;2017.12.12;
日期的格式化;SpringMVC将页面提交的值需要转换为指定的类型;
2017-12-12—Date; 类型转换,格式化;
6.8.CRUD-员工删除
7,错误处理机制
7.1 SpringBoot默认处理机制
- 浏览器,返回一个默认的错误页面
浏览器发送的请求头:
- 如果其它客户端,默认响应一个json数据
原理:可以参照ErrorMvcAutoConfiguration;错误处理的自动配置
给容器中添加了一下组件
(1) DefaultErrorAttributes:
(2)BasicErrorController:处理默认/error请求
(3)ErrorPageCustomizer:
(4)DefaultErrorViewResolver
步骤:
一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error 请求;就会被BasicErrorController处理;
响应页面;去哪个页面是由DefaultErrorViewResolver解析得到的;
7.2 如果定制错误响应
-
如何定制错误的页面
(1) 有模板引擎的情况下;error/状态码; 【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的 error文件夹下】,发生此状态码的错误就会来到 对应的页面;我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态 码.html);
页面能获取的信息;
timestamp:时间戳status:状态码
error:错误提示exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里(2)没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找;
(3)以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面; -
如何定制错误的json数据
(1) 自定义异常处理&返回定制json数据:
(2)转发到/error进行自适应响应效果处理
3. 将我们的定制数据携带出去
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由 getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;
2、页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;
容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;
自定义ErrorAttributes
终的效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容,
8.配置嵌入式Servlet容器
SpringBoot默认使用Tomcat作为嵌入式的Servlet容器
8.1 如何定制和修改Servlet容器的相关配置
- 修改和server有关的配置(ServerProperties【也是EmbeddedServletContainerCustomizer】)
- 编写一个EmbeddedServletContainerCustomizer:嵌入式的Servlet容器的定制器;来修改Servlet容器的 配置
8.2 注册Servlet三大组件【Servlet、Filter、Listener】
由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文 件。
注册三大组件用以下方式
- ServletRegistrationBean
- FilterRegistrationBean
- ServletListenerRegistrationBean
SpringBoot帮我们自动SpringMVC的时候,自动的注册SpringMVC的前端控制器;DIspatcherServlet; DispatcherServletAutoConfiguration中:
8.3 替换为其他嵌入式Servlet容器
默认支持:
Jetty
Undertow
8.4 嵌入式Servlet容器自动配置原理
EmbeddedServletContainerAutoConfiguration:嵌入式的Servlet容器自动配置
- EmbeddedServletContainerFactory(嵌入式Servlet容器工厂)
2. EmbeddedServletContainer:(嵌入式的Servlet容器)
3. 以TomcatEmbeddedServletContainerFactory为例
4. 我们对嵌入式容器的配置修改是怎么生效?
5. 容器中导入了EmbeddedServletContainerCustomizerBeanPostProcessor
步骤:
1)、SpringBoot根据导入的依赖情况,给容器中添加相应的 EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactory】
2)、容器中某个组件要创建对象就会惊动后置处理器; EmbeddedServletContainerCustomizerBeanPostProcessor; 只要是嵌入式的Servlet容器工厂,后置处理器就工作;
3)、后置处理器,从容器中获取所有的EmbeddedServletContainerCustomizer,调用定制器的定制方法
8.5 嵌入式Servlet容器启动原理
什么时候创建嵌入式的Servlet容器工厂?什么时候获取嵌入式的Servlet容器并启动Tomcat;
获取嵌入式的Servlet容器工厂:
1)、SpringBoot应用启动运行run方法
2)、refreshContext(context);SpringBoot刷新IOC容器【创建IOC容器对象,并初始化容器,创建容器中的每一 个组件】;如果是web应用创建AnnotationConfigEmbeddedWebApplicationContext,否则: AnnotationConfigApplicationContext
3)、refresh(context);刷新刚才创建好的ioc容器;
4)、 onRefresh(); web的ioc容器重写了onRefresh方法
5)、webioc容器会创建嵌入式的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容器
9. 使用外置的Servlet容器
嵌入式Servlet容器:应用打成可执行的jar
优点:简单、便携;
缺点:默认不支持JSP、优化定制比较复杂(使用定制器【ServerProperties、自定义 EmbeddedServletContainerCustomizer】,自己编写嵌入式Servlet容器的创建工厂 【EmbeddedServletContainerFactory】);
外置的Servlet容器:外面安装Tomcat—应用war包的方式打包;
步骤
1)、必须创建一个war项目;(利用idea创建好目录结构)
2)、将嵌入式的Tomcat指定为provided;
3)、必须编写一个SpringBootServletInitializer的子类,并调用configure方法
4)、启动服务器就可以使用;
原理
jar包:执行SpringBoot主类的main方法,启动ioc容器,创建嵌入式的Servlet容器;
war包:启动服务器,服务器启动SpringBoot应用【SpringBootServletInitializer】,启动ioc容器; servlet3.0(Spring注解版):
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!\METAINF\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;创建容器
7)、Spring的应用就启动并且创建IOC容器