简介
- 创建SpringBoot应用,选中我们需要的模块
- SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
- 编写业务代码;
web自动配置规则
WebMvcAutoConfiguration
1
2
3
4
5
6
7
8
|
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
|
WebMvcProperties
1
2
3
4
5
|
@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {
|
1
2
|
@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {
|
ViewResolver自动配置
静态资源自动映射
1
2
3
|
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
//可以设置和静态资源有关的参数,缓存时间等
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
|
webjars官网:http://www.webjars.org/
webjars:以jar包的方式引入静态资源;
例如引入jquery.js
1
2
3
4
5
6
|
<!--引入jquery-webjar,在访问的时候只需要写webjars下面资源的名称即可-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
|
所有请求 /webjars/**
,都去 classpath:/META-INF/resources/webjars/
找资源;

可以使用localhost:8080/webjars/jquery/3.3.1/jquery.js
进行访问
继续跟addResourceHandlers方法,可知静态资源(/**
)默认会从如下位置查找
1
2
3
4
5
|
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
|
“/**” 访问当前项目的任何资源,都去(静态资源的文件夹)找映射,例如localhost:8080/abc
=== 去静态资源文件夹里面找abc文件
HttpMessageConverter自动配置
静态首页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@Configuration(proxyBeanMethods = false)
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
return welcomePageHandlerMapping;
}
private Optional<Resource> getWelcomePage() {
String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}
|
由源码可知也是从以下路径中找第一个index.html
1
2
|
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
|
favicon
在2.x以前的版本。直接将你需要的favicon.ico文件倒挡static下面就可以。
2.X以后的版本,取消了自动配置,需要人手动去在每一个页面添加;可以使用模板
1
2
3
4
5
6
7
8
9
10
11
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>主页</title>
<link rel="shortcut icon" th:href="@{/favicon.ico}"/>
</head>
<body>
<h2>This is a homepage!!</h2>
</body>
</html>
|
配置好了刷新页面如果没有显示可以清除浏览器缓存
注意
经过maven的filter,会破坏二进制格式的文件例如图片,导致前台解析出错。
解决办法:在pom文件中配置maven的filter,在<build>
标签内添加如下配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<build>
<resources>
<!-- 显示图标-->
<resource>
<!--设定主资源目录-->
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<!--
maven default生命周期,process-resources阶段执行maven-resources-plugin插件的resources目
标处理主资源目下的资源文件时,是否对主资源目录开启资源过滤
-->
<filtering>false</filtering>
</resource>
</resources>
</build>
|
错误处理
模板引擎Thymeleaf
常用的模板引擎有:JSP、Velocity、Freemarker、Thymeleaf

SpringBoot推荐的Thymeleaf;因为语法更简单,功能更强大;
整合Thymeleaf
Use Thymeleaf 3 官方文档
引入thymeleaf
1
2
3
4
5
6
7
8
9
10
11
12
|
<properties>
<!--切换thymeleaf版本-->
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<!-- thymeleaf2 layout1-->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
|
注意
注意如果在2.3.4版本中使用上述版本控制会报错
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
***************************
APPLICATION FAILED TO START
***************************
Description:
An attempt was made to call the method org.thymeleaf.spring5.SpringTemplateEngine.setRenderHiddenMarkersBeforeCheckboxes(Z)V but it does not exist. Its class, org.thymeleaf.spring5.SpringTemplateEngine, is available from the following locations:
jar:file:/D:/OpenSources/MyRepository/org/thymeleaf/thymeleaf-spring5/3.0.9.RELEASE/thymeleaf-spring5-3.0.9.RELEASE.jar!/org/thymeleaf/spring5/SpringTemplateEngine.class
It was loaded from the following location:
file:/D:/OpenSources/MyRepository/org/thymeleaf/thymeleaf-spring5/3.0.9.RELEASE/thymeleaf-spring5-3.0.9.RELEASE.jar
Action:
Correct the classpath of your application so that it contains a single, compatible version of org.thymeleaf.spring5.SpringTemplateEngine
|
解决方案:
1
2
3
4
|
<properties>
<springboot-thymeleaf.version>3.0.9.RELEASE</springboot-thymeleaf.version>
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>
|
问题分析:
1
|
这里用的是org.springframework.boot下的spring-boot-starter-thymeleaf,使用<thymeleaf.version>做标签时可能与org.thymeleaf有冲突,导致包获取不正确
|
使用Thymeleaf
查看thymeleaf的属性配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
/**
* Whether to check that the template exists before rendering it.
*/
private boolean checkTemplate = true;
/**
* Whether to check that the templates location exists.
*/
private boolean checkTemplateLocation = true;
|
可以在配置文件中显示配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# thymeleaf配置
# 这个开发配置为false,避免改了模板还要重启服务器
spring.thymeleaf.cache=false
# 这个是配置模板路径的,默认就是templates,可不用配置
spring.thymeleaf.prefix=classpath:/templates/
# 这个可以不配置,检查模板位置
spring.thymeleaf.check-template-location=true
# 下面3个不做解释了,可以不配置
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.content-type=text/html
#server.context-path=/mapper
# 模板的模式
spring.thymeleaf.mode=HTML
|
只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
使用:
-
导入thymeleaf的名称空间
1
|
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
-
使用thymeleaf语法;
1
2
3
4
5
6
7
8
9
10
11
12
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>主页</title>
<link rel="icon" href="favicon.ico"/>
</head>
<body>
<h2>This is a homepage!!</h2>
<div th:text="${hello}">这是显式欢迎信息</div>
</body>
</html>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.eh.springboot;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Map<String, Object> map) {
map.put("hello", "你好");
return "success";
}
}
|
基本语法
th:text;改变当前元素里面的文本内容;
th:任意html属性;来替换原生属性的值,例如th:id,th:class

表达式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
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: _ # 例如三元运算符条件不成立则什么都不做
|
定制web扩展配置
-
WebMvcConfigurerAdapter,Spring Boot提供了很多xxxConfigurerAdapter来定制配置
-
定制SpringMVC配置
-
@EnableWebMvc全面接管SpringMVC
-
注册view-controller、interceptor等
扩展springmvc
1
2
3
|
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.
|
eg:
原始做法
1
2
3
4
5
6
7
|
<mvc:view-controller path="/hello" view-name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
|
官方推荐使用注解的方式,高版本springboot中使用WebMvcConfigurationSupport
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package com.eh.springboot;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
//使用WebMvcConfigurationSupport可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送 /ok 请求来到 success
registry.addViewController("/ok").setViewName("success");
}
}
|
注意:一个项目中只能有一个继承WebMvcConfigurationSupport的@Configuration类(使用@EnableMvc效果相同),如果存在多个这样的类,只有一个配置可以生效。推荐使用implements WebMvcConfigurer 的方法自定义mvc配置。
全面接管springmvc
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了
我们需要在配置类中添加@EnableWebMvc即可(如果使用WebMvcConfigurerAdapter的话,使用WebMvcConfigurationSupport已经完成全面接管了);
原理:为什么@EnableWebMvc自动配置就失效了;
@EnableWebMvc的核心
1
2
3
4
5
6
|
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
|
1
2
|
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
|
1
2
3
4
5
6
7
8
9
|
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
//关键:容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
|
可以看到使用EnableWebMvc将WebMvcConfigurationSupport导入进来了,WebMvcAutoConfiguration在没有WebMvcConfigurationSupport这个bean的时候才会起作用。
如何修改SpringBoot的默认配置
SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置
CRUD
上bootstramp官网下载一个登录示例,https://getbootstrap.com/docs/4.5/examples/
将静态资源导入到自己的工程里,参考:springboot_demo’s resources
默认访问首页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.eh.springboot;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//使用WebMvcConfigurationSupport可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送 /ok 请求来到 success
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
|
国际化
-
application配置
1
2
|
# spring Internationalized Page Value i18n
spring.messages.basename=i18n.login, i18n.language
|
-
添加i18n
resources
下添加 i18n
文件夹, 在 i18n
添加 login.properties
文件, 之后自动出现 Resource Bundle ‘language’, 从text界面切换到Resource Bundle快速添加语言
-
thymeleaf使用#
表达式接受i18n写入的值
以用户名为例:<label class="sr-only" th:text="#{login.username}">Username</label>
-
配置自定义的国际化解析器
SpringBoot自动配置好了管理国际化资源文件的组件;默认的就是根据请求头带来的区域信息获取Locale进行国际化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
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;
}
|
我们使用自定义的国际化解析器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
package com.eh.springboot.component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class I18NLocaleResolver implements LocaleResolver {
private static final String PATH_PARAMETER_SPLIT = "_";
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
Locale locale = request.getLocale();
if (!StringUtils.isEmpty(l)) {
String[] split = l.split(PATH_PARAMETER_SPLIT);
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
|
-
将自定义解析器加入到容器中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//使用WebMvcConfigurationSupport可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送 /ok 请求来到 success
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
// 将自定义解析器加入到容器中
@Bean
public LocaleResolver localeResolver() {
return new I18NLocaleResolver();
}
}
|
-
进行访问

登陆功能
开发期间模板引擎页面修改以后,要实时生效,可以执行如下操作步骤实现
-
禁用模板引擎的缓存
1
|
spring.thymeleaf.cache=false
|
-
页面修改完以后工程重新编译,cmd+F9
登录错误消息提示
1
|
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
|
拦截器实现登录检查
自定义拦截器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package com.eh.springboot.component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 登陆检查,
*/
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", "没有权限请先登陆");
// 要将msg传到login.html使用转发
request.getRequestDispatcher("/index.html").forward(request, response);
return false;
} else {
//已登陆,放行请求
return true;
}
}
}
|
注册拦截器
1
2
3
4
5
6
7
8
|
@Override
public void addInterceptors(InterceptorRegistry registry) {
//super.addInterceptors(registry);
//静态资源; *.css , *.js
//低版本中 SpringBoot已经做好了静态资源映射但是2.x又拦截了,需要将静态资源也排除
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html", "/", "/user/login","/webjars/**", "/assets/**");
}
|
session设置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@PostMapping("/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String, Object> map, HttpSession session) {
if (!StringUtils.isEmpty(username) && "123".equals(password)) {
//登陆成功,防止表单重复提交,可以重定向到主页,需要在视图解析器重配置映射main -> dashboard
session.setAttribute("loginUser", username);
return "redirect:/main.html";
} else {
//登陆失败
map.put("msg", "用户名密码错误");
return "login";
}
}
|
登录成功后显示用户名
bar.html
1
|
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
|
拦截效果:

成功登录效果

CRUD-员工列表
实验要求
-
RestfulCRUD:CRUD满足Rest风格;
URI: /资源名称/资源标识 HTTP请求方式区分对资源CRUD操作
普通CRUD(uri来区分操作) |
RestfulCRUD |
|
查询 |
getEmp |
emp—GET |
添加 |
addEmp?xxx |
emp—POST |
修改 |
updateEmp?id=xxx&xxx=xx |
emp/{id}—PUT |
删除 |
deleteEmp?id=1 |
emp/{id}—DELETE |
-
请求架构;
实验功能 |
请求URI |
请求方式 |
查询所有员工 |
emps |
GET |
查询某个员工(来到修改页面) |
emp/1 |
GET |
来到添加页面 |
emp |
GET |
添加员工 |
emp |
POST |
来到修改页面(查出员工进行信息回显) |
emp/1 |
GET |
修改员工 |
emp |
PUT |
删除员工 |
emp/1 |
DELETE |
thymeleaf公共页面元素抽取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1、抽取公共片段
<div th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</div>
2、引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名
3、默认效果:
insert的公共片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{}:
行内写法可以加上:[[~{}]];[(~{})];
|
三种引入公共片段的th属性方式对比:
th:insert:将公共片段整个插入到声明引入的元素中
th:replace:将声明引入的元素替换为公共片段
th:include:将被引入的片段的内容包含进这个标签中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<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>
|
引入片段的时候传入参数,让侧边栏某个菜单高亮:
页面在引入片段的时候传入activeUri参数,在抽取的公共片段bar.html里判断传入的参数决定是否高亮,如下所示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<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>
|
添加员工
从bootstrap官网copy一段form表单,参考地址
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
<!--需要区分是员工修改还是添加;-->
<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 01:01:10
可以在配置文件中进行配置:
1
|
spring.mvc.format.date-time=yyyy-MM-dd
|

修改员工

由于修改和添加是二合一的页面,几点需要注意:
-
判断是修改还是添加,根据emp是否为空进行判断,否则在添加逻辑会报空指针
-
底部的添加按钮需要改成修改
1
|
<button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button>
|
-
发送put请求
servlet只有post和get两种请求方式,spring mvc通过在表单中添加hidden标签和hidden过滤器实现了多种请求方式,springboot帮我们实现了过滤器功能,但是我们需要自己添加hidden标签
注意:springboot2以上默认不配置HiddenHttpMethodFilter,需要手动配置spring.mvc.hiddenmethod.filter.enabled=true
1
2
3
4
5
6
7
8
9
|
<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}">
|
删除员工
同put一样,需要添加hidden标签传入_method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<!--每个删除都写一个表单太麻烦,可以将表单抽取出来-->
<!--1. 删除按钮,注意这里使用th:attr传递属性值-->
<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>
<!--公共表单-->
<form id="deleteEmpForm" method="post">
<input type="hidden" name="_method" value="delete"/>
</form>
<!--js-->
<script>
$(".deleteBtn").click(function(){
//删除当前员工的
$("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
return false;
});
</script>
|
错误处理机制
spring默认的错误处理机制
默认效果
原理
可以参照ErrorMvcAutoConfiguration;错误处理的自动配置
给容器中添加了以下组件:
-
DefaultErrorAttributes
1
2
3
4
5
6
7
8
9
10
11
|
帮我们在页面共享信息;
@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;
}
|
-
BasicErrorController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@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);
}
|
-
ErrorPageCustomizer
1
2
|
@Value("${error.path:/error}")
private String path = "/error"; 系统出现错误以后来到error请求进行处理;(web.xml注册的错误页面规则)
|
-
DefaultErrorViewResolver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
@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解析得到的;
1
2
3
4
5
6
7
8
9
10
11
|
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;
}
|
定制错误响应
定制错误页面
-
有模板引擎的情况下;error/状态码; 【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的 error文件夹下】,发生此状态码的错误就会来到 对应的页面;
我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html);
页面能获取的信息如下:
- timestamp:时间戳
- status:状态码
- error:错误提示
- exception:异常对象
- message:异常消息
- errors:JSR303数据校验的错误都在这里
-
没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找;
-
以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面;
定制错误的json数据
自定义异常处理&返回定制json数据;
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotExistException.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;
}
}
//没有自适应效果...
|
转发到/error进行自适应响应效果处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@ExceptionHandler(UserNotExistException.class)
public String handleException(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";
}
|
2.x版本需要将异常信息显示设置为true
1
2
3
|
# 显示异常的信息
server.error.include-exception=true
server.error.include-message=always
|
将定制数据携带出去
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
方式一:完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;
方式二:页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;
自定义ErrorAttributes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package com.eh.springboot.exception;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
import static org.springframework.boot.web.error.ErrorAttributeOptions.Include.*;
import java.util.Map;
//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
//返回值的map就是页面和json能获取的所有字段
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
// 默认返回的错误信息
Map<String, Object> map = super.getErrorAttributes(webRequest, options);
// 添加自定义信息
map.put("company", "cana");
//我们的异常处理器携带的数据
Map<String, Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", 0);
map.put("ext", ext);
return map;
}
}
|
最终的效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容,
1
2
3
4
5
6
7
8
9
10
11
12
13
|
{
"timestamp": "2020-10-24T06:15:12.716+00:00",
"status": 500,
"error": "Internal Server Error",
"exception": "com.eh.springboot.exception.UserNotExistException",
"message": "用户不存在",
"path": "/cana/hello",
"company": "cana",
"ext": {
"code": "user not exist",
"message": "用户出错啦"
}
}
|
技巧
这里可以使用idea自带的类似postman工具
从顶层工具栏依次 Tools -> HTTP Client -> Test RESTFUL Web Service 打开
配置嵌入式Servlet容器
SpringBoot默认使用Tomcat作为嵌入式的Servlet容器;

问题:如何修改和定制Servlet容器的相关配置
EmbeddedServletContainerCustomizer
修改和server有关的配置(ServerProperties【也是EmbeddedServletContainerCustomizer】);
1
2
3
4
5
6
7
8
9
10
|
server.port=8081
server.context-path=/crud
server.tomcat.uri-encoding=UTF-8
//通用的Servlet容器设置
server.xxx
//Tomcat的设置
server.tomcat.xxx
|
ConfigurableEmbeddedServletContainer
定制
编写一个EmbeddedServletContainerCustomizer:嵌入式的Servlet容器的定制器;来修改Servlet容器的配置
1
2
3
4
5
6
7
8
9
10
11
|
@Bean //一定要将这个定制器加入到容器中
public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
return new EmbeddedServletContainerCustomizer() {
//定制嵌入式的Servlet容器相关的规则
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(8083);
}
};
}
|
SpringBoot升级到2.0系列后不在支持EmbeddedServletContainerCustomizer。WebServerFactoryCustomizer也就是一种定制器类:需要通过新建自定义的WebServerFactoryCustomizer类来实现属性配置修改。
1
2
3
4
5
|
//配置嵌入式的Servlet容器
@Bean
public WebServerFactoryCustomizer webServerFactoryCustomizer() {
return (WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>) factory -> factory.setPort(8896);
}
|
注册Servlet三大组件【Servlet、Filter、Listener】
由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。
注册三大组件用以下方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
package com.eh.springboot.config;
import com.eh.springboot.filter.MyFilter;
import com.eh.springboot.linstener.MyListener;
import com.eh.springboot.servlet.MyServlet;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
public class MyServerConfig {
//注册三大组件
@Bean
public ServletRegistrationBean myServlet() {
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet");
registrationBean.setLoadOnStartup(1);
return registrationBean;
}
@Bean
public FilterRegistrationBean myFilter() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello", "/myServlet"));
return registrationBean;
}
@Bean
public ServletListenerRegistrationBean myListener() {
ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}
//配置嵌入式的Servlet容器
@Bean
public WebServerFactoryCustomizer webServerFactoryCustomizer() {
return (WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>) factory -> factory.setPort(8896);
}
}
|
使用其他Servlet容器

-
Jetty(长连接,点对点聊天)
-
Undertow(高性能非阻塞,不支持JSP)
默认支持:Tomcat(默认使用)
1
2
3
4
5
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
引入web模块默认就是使用嵌入式的Tomcat作为Servlet容器;
</dependency>
|
使用Jetty
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!--引入其他的Servlet容器-->
<dependency>
<artifactId>spring-boot-starter-jetty</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>
|
使用Undertow
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<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>
|
嵌入式Servlet容器自动配置原理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
@Configuration(proxyBeanMethods = false)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnClass(ServletRequest.class)
@ConditionalOnWebApplication(type = Type.SERVLET)
@EnableConfigurationProperties(ServerProperties.class)
// BeanPostProcessorsRegistrar Spring注解版;给容器中导入一些组件
// 导入了WebServerFactoryCustomizerBeanPostProcessor
// 后置处理器:bean初始化前后(创建完对象,还没赋值赋值)执行初始化工作
@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,
ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,
ServletWebServerFactoryConfiguration.EmbeddedJetty.class,
ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })
public class ServletWebServerFactoryAutoConfiguration {
@Bean
public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(ServerProperties serverProperties) {
return new ServletWebServerFactoryCustomizer(serverProperties);
}
@Bean
// 判断当前是否引入了Tomcat依赖;
@ConditionalOnClass(name = "org.apache.catalina.startup.Tomcat")
public TomcatServletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer(
ServerProperties serverProperties) {
return new TomcatServletWebServerFactoryCustomizer(serverProperties);
}
@Bean
@ConditionalOnMissingFilterBean(ForwardedHeaderFilter.class)
@ConditionalOnProperty(value = "server.forward-headers-strategy", havingValue = "framework")
public FilterRegistrationBean<ForwardedHeaderFilter> forwardedHeaderFilter() {
ForwardedHeaderFilter filter = new ForwardedHeaderFilter();
FilterRegistrationBean<ForwardedHeaderFilter> registration = new FilterRegistrationBean<>(filter);
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC, DispatcherType.ERROR);
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
/**
* Registers a {@link WebServerFactoryCustomizerBeanPostProcessor}. Registered via
* {@link ImportBeanDefinitionRegistrar} for early registration.
*/
public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware {
private ConfigurableListableBeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof ConfigurableListableBeanFactory) {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
if (this.beanFactory == null) {
return;
}
// 实际导入了webServerFactoryCustomizerBeanPostProcessor
registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor",
WebServerFactoryCustomizerBeanPostProcessor.class);
registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor",
ErrorPageRegistrarBeanPostProcessor.class);
}
private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name, Class<?> beanClass) {
if (ObjectUtils.isEmpty(this.beanFactory.getBeanNamesForType(beanClass, true, false))) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
beanDefinition.setSynthetic(true);
registry.registerBeanDefinition(name, beanDefinition);
}
}
}
}
|
定制原理:WebServerFactoryCustomizerBeanPostProcessor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebServerFactory) {
postProcessBeforeInitialization((WebServerFactory) bean);
}
return bean;
}
@SuppressWarnings("unchecked")
private void postProcessBeforeInitialization(WebServerFactory webServerFactory) {
LambdaSafe.callbacks(WebServerFactoryCustomizer.class, getCustomizers(), webServerFactory)
.withLogger(WebServerFactoryCustomizerBeanPostProcessor.class)
.invoke((customizer) -> customizer.customize(webServerFactory));
}
private Collection<WebServerFactoryCustomizer<?>> getCustomizers() {
if (this.customizers == null) {
// Look up does not include the parent context
this.customizers = new ArrayList<>(getWebServerFactoryCustomizerBeans());
this.customizers.sort(AnnotationAwareOrderComparator.INSTANCE);
this.customizers = Collections.unmodifiableList(this.customizers);
}
return this.customizers;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Collection<WebServerFactoryCustomizer<?>> getWebServerFactoryCustomizerBeans() {
return (Collection) this.beanFactory.getBeansOfType(WebServerFactoryCustomizer.class, false, false).values();
}
|

可以看到是将WebServerFactoryCustomizer加入到server的定制器集合里,所以我们自定义WebServerFactoryCustomizer放到容器里就可以实现定制。
自动配置生效原理:以TomcatServletWebServerFactory为例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
if (this.disableMBeanRegistry) {
Registry.disableRegistry();
}
Tomcat tomcat = new Tomcat();
// //配置Tomcat的基本环节
File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
connector.setThrowOnFailure(true);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
return getTomcatWebServer(tomcat);
}
|
小结步骤, 以tomcat为例
-
SpringBoot根据导入的依赖情况,给容器中添加相应的EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactory】
-
容器中某个组件要创建对象就会惊动后置处理器;WebServerFactoryCustomizerBeanPostProcessor;
只要是嵌入式的Servlet容器工厂,后置处理器就工作;
-
后置处理器,从容器中获取所有的WebServerFactoryCustomizer,调用定制器的定制方法
嵌入式Servlet容器启动原理
什么时候创建嵌入式的Servlet容器工厂?什么时候获取嵌入式的Servlet容器并启动Tomcat;
启动步骤:
-
SpringBoot应用启动运行run方法
-
创建IOC容器SpringBootApplication.createApplicationContext
如果是web应用创建AnnotationConfigServletWebServerApplicationContext,如果是响应式web应用: AnnotationConfigReactiveWebServerApplicationContext,否则AnnotationConfigApplicationContext
-
跟到SpringBootApplication类refreshContext方法, 刷新刚才创建好的ioc容器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// web的ioc容器重写了onRefresh方法
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 我们自己写的Controller、Service会在这儿初始化
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
|
-
onRefresh();web的ioc容器重写了onRefresh方法
-
web ioc容器ServletWebServerApplicationContext会创建嵌入式的Servlet容器
1
2
3
4
5
6
7
8
9
10
|
@Override
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
|
-
获取嵌入式的Servlet容器工厂
1
|
ServletWebServerFactory factory = getWebServerFactory();
|

从ioc容器中获取ServletWebServerFactory 组件;TomcatServletWebServerFactory创建对象,后置处理器一看是这个对象,就获取所有的定制器来先定制Servlet容器的相关配置;
-
使用容器工厂获取嵌入式的Servlet容器:
1
|
this.webServer = factory.getWebServer(getSelfInitializer());
|
-
嵌入式的Servlet容器创建对象并启动Servlet容器
org.springframework.boot.web.embedded.tomcat.TomcatWebServer#initialize 启动
一言以蔽之,先启动嵌入式的Servlet容器,再将ioc容器中剩下没有创建出来的对象获取出来,也就是在IOC容器启动时先创建嵌入式的Servlet容器。
使用外部Servlet容器
嵌入式Servlet容器:应用打成可执行的jar
- 优点:简单、便携;
- 缺点:默认不支持JSP、优化定制比较复杂(使用定制器【ServerProperties、自定义 EmbeddedServletContainerCustomizer】,自己编写嵌入式Servlet容器的创建工厂 【EmbeddedServletContainerFactory】);
外置的Servlet容器:外面安装Tomcat—应用war包的方式打包;
使用外部Servlet容器快速搭建web开发环境:完整项目地址
-
使用Spring Initializer创建新项目,package选择war
-
创建的新项目里没有webapp目录和web.xml,打开项目设置

-
配置application.properties
1
2
|
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
|
步骤
-
必须创建一个war项目;(利用idea创建好目录结构)
-
将嵌入式的Tomcat指定为provided;
1
2
3
4
5
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
|
-
必须编写一个SpringBootServletInitializer的子类,并调用configure方法
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package com.eh.springbootexternal;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringbootexternalApplication.class);
}
}
|
-
启动服务器就可以使用
原理
jar包方式:执行SpringBoot主类的main方法,启动ioc容器,创建嵌入式的Servlet容器;
war包方式:启动服务器,服务器启动SpringBoot应用【SpringBootServletInitializer】,启动ioc容器;
规范
Servlet3.0标准ServletContainerInitializer扫描所有jar包中META-INF/services/javax.servlet.ServletContainerInitializer文件指定的类并加载
8.2.4 Shared libraries / runtimes pluggability:
规则:
- 服务器启动(web应用启动)会创建当前web应用里面每一个jar包里面ServletContainerInitializer实例:
- ServletContainerInitializer的实现放在jar包的META-INF/services文件夹下,有一个名为 javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInitializer的实现类的全类名
- 还可以使用@HandlesTypes,在应用启动的时候加载我们感兴趣的类;
流程
-
启动Tomcat
-
org/springframework/spring-web/5.2.9.RELEASE/spring-web-5.2.9.RELEASE.jar!/META-INF/services/javax.servlet.ServletContainerInitializer
-
SpringServletContainerInitializer将@HandlesTypes(WebApplicationInitializer.class)标注的所有这个类型的类都传入到onStartup方法的Set<Class<?>>
;为这些WebApplicationInitializer类型的类创建实例;
-
每一个WebApplicationInitializer都调用自己的onStartup;

-
相当于我们的SpringBootServletInitializer的类会被创建对象,并执行onStartup方法
-
SpringBootServletInitializer实例执行onStartup的时候会createRootApplicationContext;创建容器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
//1、创建SpringApplicationBuilder
SpringApplicationBuilder builder = createSpringApplicationBuilder();
builder.main(getClass());
ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
if (parent != null) {
this.logger.info("Root context already created (using as parent).");
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
builder.initializers(new ParentContextApplicationContextInitializer(parent));
}
builder.initializers(new ServletContextApplicationContextInitializer(servletContext));
builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class);
//调用configure方法,子类重写了这个方法,将SpringBoot的主程序类传入了进来
builder = configure(builder);
builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext));
SpringApplication application = builder.build();
if (application.getAllSources().isEmpty()
&& MergedAnnotations.from(getClass(), SearchStrategy.TYPE_HIERARCHY).isPresent(Configuration.class)) {
application.addPrimarySources(Collections.singleton(getClass()));
}
Assert.state(!application.getAllSources().isEmpty(),
"No SpringApplication sources have been defined. Either override the "
+ "configure method or add an @Configuration annotation");
// Ensure error pages are registered
if (this.registerErrorPageFilter) {
application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class));
}
application.setRegisterShutdownHook(false);
//启动Spring应用, 剩下的和嵌入式server运行原理中介绍的是一样的
return run(application);
}
|
-
Spring的应用就启动并且创建IOC容器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 刷新IOC容器
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
|
一言以蔽之,使用外部容器是先启动Servlet容器,再启动SpringBoot应用,与使用内部容器相反。