Spring Boot 4.web开发
web开发
thymeleaf、web定制、容器定制
代码地址
ssh git@gitee.com:Ding_DangMao/learn-spring-bot.git
1. 简介
使用Spring Boot
- 创建 springboot应用,选中我们需要的模块。
- spring boot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
- 编写自己业务代码
自动配置原理?
这个常见 spring boot帮我们配置了什么?能不能修改?能修改那些配置?能不能扩展?XXX
XxxAutoConfiguration 帮我们给容器中自动配置组件
XxxProperties 配置类来封装配置文件的内容
2. spring boot静态资源的映射规则
- spring boot的 mvc配置都在
WebMvcAutoConfiguration.java
里面
//添加资源映射 WebMvcAutoConfiguration类中【这个方法】
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));
}
}
}
----------原理---------
//ResourceProperties 可以设置静态资源有关的参数,缓存时间等。
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties implements ResourceLoaderAware {}
// /** 可以访问当前项目任何资源
public String getStaticPathPattern() {
return this.staticPathPattern; // this.staticPathPattern = "/**";
}
public String[] getStaticLocations() {
return this.staticLocations;
}
this.staticLocations = RESOURCE_LOCATIONS;
static {
RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length + SERVLET_RESOURCE_LOCATIONS.length];
System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0, SERVLET_RESOURCE_LOCATIONS.length);
System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length);
}
CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
SERVLET_RESOURCE_LOCATIONS = new String[]{"/"};
- 所有 /webjars/** 的资源都去 classpath:/META-INF/resources/webjars/ 找资源;
webjars:以 jar包的方式引入静态资源,
localhost:8080/webjars/jquery/3.3.1/jquery.js 拿到jquery文件在访问的时候只需要写webjars下面资源的名称即可 <!--引入 jquery-web-jar--> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
- /** 可以访问当前项目的任何资源,如果没人处理默认从【静态资源的文件夹】
localhost:8080/abc ===>去静态资源文件里面找abc"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" "/" 当前项目的根路径
- 欢迎页映射,静态资源文件夹下的所有 index.html 页面,被 /** 映射。
localhost:8080/ 默认找index页面
//配置欢迎页映射 WebMvcAutoConfiguration类中【这个方法】
@Bean
public WebMvcAutoConfiguration.WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {
return new WebMvcAutoConfiguration.WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
}
-----------原理------------
public Resource getWelcomePage() {
String[] var1 = this.getStaticWelcomePageLocations();
int var2 = var1.length;
return null;
}
private String[] getStaticWelcomePageLocations() {
String[] result = new String[this.staticLocations.length];
//staticLocations 上面有
for(int i = 0; i < result.length; ++i) {
String location = this.staticLocations[i];
if (!location.endsWith("/")) {
location = location + "/";
}
result[i] = location + "index.html";
}
return result;
}
public String getStaticPathPattern() {
return this.staticPathPattern;//this.staticPathPattern = "/**";
}
- 所有的 **/favicon.ioc 都是在静态资源文件下找
//浏览器打开左上角的图标配置 WebMvcAutoConfiguration类中【这个方法】
@Configuration
@ConditionalOnProperty(
value = {"spring.mvc.favicon.enabled"},
matchIfMissing = true
)
public static class FaviconConfiguration {
private final ResourceProperties resourceProperties;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
//所有 **/favicon.ico
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler.setLocations(this.resourceProperties.getFaviconLocations());
return requestHandler;
}
}
----------原理--------------
List<Resource> getFaviconLocations() {
List<Resource> locations = new ArrayList(this.staticLocations.length + 1);
}
String[] staticLocations; //和上面一样,
3. 模板引擎
jsp,velocity,freemarker,thymeleaf
spring boot 推荐的 thymeleaf,语法简单,功能更强大
3.1 引入 thymeleaf
<!--引入thymeleaf 版本不用管,当前我引入的 springboot1.5.9默认版本2.1.6-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--我们需要切换版本-->
<properties> 顺序这个标签在上面
<!--主程序-->
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<!--布局功能的支持程序 如果是:版本3主程序 layout2以上版本-->
<!--例如:thymeleaf2 和 layout1 适配 【layout2.0.0以上支持 thymeleaf3以上版本】-->
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>
3.2 thymeleaf 使用
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
public static final String DEFAULT_PREFIX = "classpath:/templates/"; //默认的视图前缀
public static final String DEFAULT_SUFFIX = ".html"; //默认的视图后缀
//只要我们把 html页面放在 /templates/,thymeleaf 就自动渲染了
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML5";
private Charset encoding;
private MimeType contentType;
private boolean cache;
private Integer templateResolverOrder;
private String[] viewNames;
private String[] excludedViewNames;
private boolean enabled;
}
- 导入 thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
- 使用 thymeleaf 语法
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>成功</h2> <!--th:text="" 将div里面的文本内容设置为 指定的值--> <div th:text="${hello}"> 这是显示欢迎信息 </div> </body> </html>
3.3 语法规则
- th:text :改变当前元素里面的文本内容
th :任意html属性,来替换原生属性的值
- 我们能写的表达式
Simple expressions: # 表达式语法
Variable Expressions: ${...}
1. 获取对象的属性,调用方法
2. 使用内置对象
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.
$(session.size())
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
Page 20 of 106
#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: boolean运算
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: _
练习
@Controller //代表当前类是一个控制器
public class HelloController {
@ResponseBody //hello 发送出去需要依赖 responseBody
@RequestMapping("/hello") //处理请求
public String Hello() {
return "hello world";
}
/**
* 查出一些数据,在页面展示
*
* @return
*/
@RequestMapping("/success")
public String success(Map<String, Object> map) {
// classpath:/templates/
map.put("hello", "<h1>你好</h1>");
map.put("users", Arrays.asList("张三", "李四", "王五"));
return "success";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>成功</h2>
<!--th:text="" 将div里面的文本内容设置为 指定的值-->
<div th:text="${hello}" th:id="${hello}" th:clas="${hello}">
这是显示欢迎信息
</div>
<hr>
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<hr>
<!-- th:each 每次遍历都会生成当前这个标签-->
<h4 th:text="${user}" th:each="user:${users}"></h4>
<hr>
<!-- 英式符号写在里会转移,所以记录中文
【【美元符{...}】】 ,双中括号,就是 th:text 会转义
【(美元符{...})】 ,中括号小括号,就是 th:utext 不会转义
-->
<h4>
<span th:each="user:${users}">[[${user}]]</span>
</h4>
</body>
</html>
4. spring mvc自动配置
地址 https://docs.spring.io/spring-boot/docs/2.5.6/reference/htmlsingle/#features.developing-web-applications.spring-mvc
Spring MVC Auto-configuration
Spring Boot 自动配置好了 springMVC
以下是 spring boot对springMVC的默认配置
-
Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.- 自动配置了 ViewResolver【视图解析器:根据方法的返回值的到视图对象 view】,视图对象决定如何渲染【转发重定向】
- ContentNegotiatingViewResolver:组合所有的视图解析器的
- 如何定制,我们可以自己给容器种添加一个视图解析器,自动的将其组合进来
-
Support for serving
static resources
, including support forWebJar
s (covered later in this document).- 静态资源文件夹路径,webjars
-
自动注册了
Converter
,GenericConverter
, andFormatter
beans.- Converter 转换器;public String hello(User user);类型转换使用 Converter
- Formatter 格式化器;2017.12.17=Data;
自己添加的格式化转换器,我们只需要放在容器中即可。@Bean @ConditionalOnProperty( prefix = "spring.mvc", name = {"date-format"}//在文件中配置日期格式化规则 ) public Formatter<Date> dateFormatter() { //日期格式化组件 return new DateFormatter(this.mvcProperties.getDateFormat()); }
-
Static
Faviccon
support (see below) favicon.ico -
Support for
HttpMessageConverters
(covered later in this document).- HttpMessageConverters:springmvc用来转换 http请求和响应的:user-login
- HttpMessageConverters 是从容器中确定的;底层就是获取所有的 httpMessageConverter
自己给容器中添加 httpMessageConverter,只需要将自己的组件注册容器中【@Bean,@Component】
-
Automatic registration of
MessageCodesResolver
(covered later in this document).- 定义错误代码生成规则
-
Static
index.html
support. 静态首页访问的 -
Automatic use of a
ConfigurableWebBindingInitializer
bean (covered later in this document).- 我们也可以配置一个 ConfigurableWebBindingInitializer【它是从容器中拿的】来替换默认配置,添加到容器中
- 初始化 WebDataBinder;请求数据 == JavaBean
-
spring-boot-autoconfigure-1.5.10.RELEASE.jar!\org\springframework\boot\ autoconfigure\web 自动配置web的所有场景
-
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own
@Configuration
class of type WebMvcConfigurer but without@EnableWebMvc
. -
If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.
-
If you want to take complete control of Spring MVC, you can add your own
@Configuration
annotated with@EnableWebMvc
, or alternatively add your own@Configuration
-annotated DelegatingWebMvcConfiguration as described in the Javadoc of@EnableWebMvc
.
4.1 spring mvc auto-configuration
4.2 扩展 spring mvc
<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
既保留了所有的自动配置,也能用我们扩展的配置
* 使用 WebMvcConfigurerAdapter可以来扩展 springmvc的功能
*/
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送请求 /cainiao 来到 success页面
registry.addViewController("/cainiao").setViewName("success");
}
}
原理
- WebMvcAutoConfiguration 是springmvc的自动配置类
- 在做其他自动配置时会导入:@Import(EnableWebMvcConfiguration.class)
@Configuration @Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class}) @EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class}) public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {} ----------原理----------- @Configuration public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {} @Configuration public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport { private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite(); //从容器中 获取所有的 webmvcconfigurer @Autowired(required = false) //自动装配, public void setConfigurers(List<WebMvcConfigurer> configurers) { if (!CollectionUtils.isEmpty(configurers)) { this.configurers.addWebMvcConfigurers(configurers); } } //一个参考实现 将所有的 WebMvcConfigurer相关配置都来一起调用。 @Override protected void addViewControllers(ViewControllerRegistry registry) { this.configurers.addViewControllers(registry); } } @Override public void addViewControllers(ViewControllerRegistry registry) { for (WebMvcConfigurer delegate : this.delegates) { delegate.addViewControllers(registry); } }
- 容器中所有的 WebMvcConfigurer都会一起起作用
- 我们的配置类也会被调用;效果,springmvc的自动配置和我们的扩展配置都会起作用。
4.3 全面接管 spring mvc
- spring boot对springmvc的自动配置不需要,所有都是我们自己配,所有的 springmvc的自动配置都失效了。我们需要在配置类中添加 @EnableWebMvc 即可 。
原理 - 为什么加上 @EnableWebMvc自动配置就就失效了,
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class) enablewebmvc 的核心
public @interface EnableWebMvc {
}
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
}
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
WebMvcConfigurerAdapter.class })
//主要因为这个 容器中没有这个 bean的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {}
- @EnableWebMvc 将 WebMvcConfigurationSupport 组件导入进来。
- 导入的 WebMvcConfigurationSupport只是springmvc的基本功能。
5. 如何修改 spring boot的默认配置
模式
- spring boot在自动配置很多组件的时候,想看容器中有没有用户字节配置的【@Bean,@Component】如果有就用用户配置的,如果没有,才自动配置。如果有些组件可以有多个【viewResolver】将用户配置和自己配置的组合起来。
- 在 spring boot会有非常多的 xxConfigurer帮助我们进行扩展配置
- 在 spring boot中会有很多的 xxCustomizer帮助我们进行定制配置
6. RestfulCRUD
- 默认访问首页
/**
* @author shkstart
* @create 2021-10-26 19:31
* 使用 WebMvcConfigurerAdapter可以来扩展 springmvc的功能
*/
//@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送请求 /cainiao 来到 success页面
registry.addViewController("/cainiao").setViewName("success");
}
//所有的 WebMvcConfigurerAdapter组件会一起起作用
@Bean //将组建注册在容器中
public WebMvcConfigurerAdapter getWebMvcConfigurerAdapter() {
return new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
};
}
}
6.1 默认访问首页
6.2 国际化
- 编写国际化配置文件
- 使用 ResourceBundleMessageSource 管理国际化资源文件
- 在页面使用 fmt:message 取出国际化内容
步骤
- 编写国际化配置文件,抽取页面需要显示的国际化消息
- spring boot自动配置好了管理国际化资源文件的组件
@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
/**
* Comma-separated list of basenames, each following the ResourceBundle convention.
* Essentially a fully-qualified classpath location. If it doesn't contain a package
* qualifier (such as "org.mypackage"), it will be resolved from the classpath root.
*/
private String basename = "messages";
//我们的配置文件可以直接放在类路径下叫 message.properties
//管理国际化资源文件的 source
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) {
//设置国际化资源文件的基础名【去掉国家代码的】
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(this.basename)));
}
if (this.encoding != null) {
messageSource.setDefaultEncoding(this.encoding.name());
}
messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
messageSource.setCacheSeconds(this.cacheSeconds);
messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
return messageSource;
}
}
#application.properties 文件
指定国际化文件的的路径
spring.messages.basename=i181.login
- 去页面获取国际化的值
使用 #{} 获取值【login.html,index.html换成了login.html】
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<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" th:action="@{/user/login}" method="post">
<img class="mb-4" src="asserts/img/bootstrap-solid.svg" th:href="@{/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>
<!--做一个判断-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" th:placeholder="#{login.username}" placeholder="Username" required=""
name="username" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" th:placeholder="#{login.password}" placeholder="Password"
name="password" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> [[#{login.remember}]] <!-- Remember me-->
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
</form>
</body>
</html>
乱码问题解决
#application.properties 文件
#i18n 乱码问题
spring.messages.encoding=utf-8
效果:根据浏览器语言设置的信息切换了国际化
- 原理:
国际化 Locale【区域信息对象】LocaleResolver【获取区域对象】@Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "spring.mvc", name = "locale") public LocaleResolver localeResolver() { if (this.mvcProperties .getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) { return new FixedLocaleResolver(this.mvcProperties.getLocale()); } AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); localeResolver.setDefaultLocale(this.mvcProperties.getLocale()); return localeResolver; } // 默认的就是根据请求头带来的区域信息获取 locale进行国际化
- 点击连接切换国际化【自己编写一个 LocaleResolver 加到容器中】
<!--login.html--> <p class="mt-5 mb-3 text-muted">© 2017-2018</p> <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a> <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
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 MyLocaleResolver implements LocaleResolver { //解析区域信息的 @Override public Locale resolveLocale(HttpServletRequest request) { String l = request.getParameter("l"); //获取到就根据获取到的,没有,默认的 Locale locale = Locale.getDefault(); if (!StringUtils.isEmpty(l)) { String[] split = l.split("_"); //第一参数,语言代码,第二个,国家代码 locale = new Locale(split[0], split[1]); System.out.println("使用自定义的 local"); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { } } //名字 localeResolver 指明一下 否则会使用spring boot默认的 @Bean(name = "localeResolver") public LocaleResolver localResolver() { return new MyLocaleResolver(); }
6.3 登录
"开发技巧"
- 开发期间模板页面修改以后,要实时生效
- 禁用模板引擎的缓存
#禁用掉模板缓存 spring.thymeleaf.cache=false
- 修改页面完成以后 ctrl + f9 重新加载页面
- 禁用模板引擎的缓存
- 登录错误消息的显示
<!--做一个判断--> <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
6.4 拦截器进行检查
/**
* @author shkstart
* @create 2021-10-27 21:02
* 拦截器:登录检查
*/
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);
} else {
//已登录,放行请求
return true;
}
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
//所有的 WebMvcConfigurerAdapter组件会一起起作用
@Bean //将组建注册在容器中
public WebMvcConfigurerAdapter getWebMvcConfigurerAdapter() {
return 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 [spring boot已经做好了静态资源映射]
registry.addInterceptor(new LoginHandlerInterceptor())
// /** 拦截任意目录下的所有请求
.addPathPatterns("/**").excludePathPatterns("/index.html", "/user/login");
}
};
}
6.5 crud-员工列表
实现要求:
- restfulCRUD;crud满足 rest风格
url:/资源名称/资源标识 ===》http请求方式区分对资源 crud操作
普通CRUD(uri来区分操作) | RestfulCRUD | |
---|---|---|
查询 | getEmp | emp--GET |
添加 | addEmp?xxx | emp-Post |
修改 | updateEmp?id=xxx&xx=xx | emp/{id}---PUT |
删除 | deleteEmp?id=1 | emp/{id}---DELETE |
- 实验的请求架构:
# | 请求url | 请求方式 |
---|---|---|
查询所有员工 | emps | GET |
查询某个员工(来到修改页面 | epm/ | GET |
来到添加页面 | emp1 | GET |
添加员工 | emp | POST |
来到修改页面(查询出员工进行信息回显 | emp/ | GET |
修改员工 | emp | PUT |
删除员工 | emp/ | DELETE |
- 员工列表
thymeleaf 公共页面元素抽取
thymeleaf 公共页面元素抽取
1. 抽取公共页面
<div th:foragment="copy">
©2011 the good thymes virtual grocery
</div>
2. 引入公告片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::select} 模板名::选择器
~{templatename::fragmentname} 模板名::片段名
或者
<div th:insert="footer :: copy"></div>
3. 默认效果
insert 的功能片段在 div标签中
如果使用 th:insert 等属性进行引入,可以不用写 ~{}
行内写法可以加上:[[~{}]] [(~{})]
三种引入片段的 th属性
- th:insert 将公共的片段整个插入到声明引入的元素中
- th:replace 将声明引入的元素替换为公共片段
- th:inlude 将被引入的片段的内容包含进这个标签中
<footer th:fragment="copy">
© 2021 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>
© 2021 the good thymes virtual grocery
</footer>
</div>
<footer>
© 2021 the good thymes virtual grocery
</footer>
<div>
© 2021 the good thymes virtual grocery
</div>
引入片段的时候传入参数
<div th:fragment="frga(onevar,twovar)">
<p th:text"${onevar}+'-'+${twovar}">
</p>
</div>
<div th:replace="::frag(${value1},${value2})"></div>
<div th:replace="::frga(onevar=${value1},twovar=${value2})"></div>
或者
<div th:fragment="frag"></div>
<div th:replace="::frag(onevar=$(value1),twovar=${value2})"> </div>
6.6 curd-员工添加
<form th:action="@{/emp}" method="post">
<div class="form-group">
<label for="exampleFormControlInput1">Last Name</label>
<input name="lastName" type="text" class="form-control" id="exampleFormControlInput1"
placeholder="zhangsan">
</div>
<div class="form-group">
<label>Email</label>
<input name="email" type="email" class="form-control" placeholder="name@example.com">
</div>
<div class="form-group">
<label>Gender</label>
<div class="form‐check form‐check‐inline">
<input class="form‐check‐input" type="radio" name="gender" value="1">
<label class="form‐check‐label">男</label>
</div>
<div class="form‐check form‐check‐inline">
<input class="form‐check‐input" type="radio" name="gender" value="0">
<label class="form‐check‐label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<select multiple class="form-control" name="department.id">
<option th:value="${dept.id}" th:each="dept:${depts}"
th:text="${dept.getDepartmentName()}"></option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input name="birth" type="text" class="form-control" placeholder="yyyy/MM/dd">
</div>
<button type="submit" class="btn btn-primary">添加</button>
</form>
- 提交的数据格式不对:生日,日期【默认没有配是斜线】
2012-12-21、2012/12/23、2012.12.12
日期的格式化,springmvc将页面提交的值需要转为指定的类型
2012-12-12 === date 类型转换,格式化
默认日期是按照 / 的方式
WebMvcAutoConfiguration 类中配置了一个类@Bean @ConditionalOnProperty(prefix = "spring.mvc", name = "date-format") public Formatter<Date> dateFormatter() { return new DateFormatter(this.mvcProperties.getDateFormat()); } public String getDateFormat() { return this.dateFormat; } /** * Date format to use (e.g. dd/MM/yyyy). */ private String dateFormat;
- springboot 的 application.properties文件修改 mvc默认的解析格式
#直接指定一下 mvc的日期解析格式 spring.mvc.date-format=yyyy-MM-dd
转发原理
//redirect 表示重定向到一个地址,forward 表示转发到一个地址 /代表当前路径
原理:ThymeleafViewResolver extends AbstractCachingViewResolver implements Ordered
该类属性
String REDIRECT_URL_PREFIX = "redirect:";
String FORWARD_URL_PREFIX = "forward:";
该类方法
protected View createView(final String viewName, final Locale locale) throws Exception {
RedirectView view = new RedirectView
}
RedirectView类的该方法
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws IOException {
sendRedirect(request, response, targetUrl, this.http10Compatible);
}
protected void sendRedirect(HttpServletRequest request, HttpServletResponse response,
String targetUrl, boolean http10Compatible) throws IOException {
response.sendRedirect(encodedURL); //重定向
}
6.7 crud-员工修改
<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<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>Dashboard Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="asserts/css/bootstrap.min.css" rel="stylesheet" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}">
<!-- Custom styles for this template -->
<link href="asserts/css/dashboard.css" rel="stylesheet" th:href="@{/asserts/css/dashboard.css}">
<style type="text/css">
/* Chart.js */
@-webkit-keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}
@keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}
.chartjs-render-monitor {
-webkit-animation: chartjs-render-animation 0.001s;
animation: chartjs-render-animation 0.001s;
}
</style>
</head>
<body>
<!--引入抽取的 topbar-->
<!--模版名:会使用 thymeleaf的前后缀配置规则进行解析-->
<div th:replace="commons/bar::topbar"></div>
<div class="container-fluid">
<div class="row">
<!--引入侧边栏-->
<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">
<div class="table-responsive">
<!--需要区分员工修改还是添加-->
<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 for="exampleFormControlInput1">Last Name</label>
<input name="lastName" type="text" class="form-control" id="exampleFormControlInput1"
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="name@example.com"
th:value="${emp!=null}?${emp.email}" }>
</div>
<div class="form-group">
<label>Gender</label>
<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>
<select multiple class="form-control" name="department.id">
<option th:value="${dept.id}" th:each="dept:${depts}"
th:text="${dept.getDepartmentName()}"
th:selected="${emp!=null}?${dept.id==emp.department.id}"></option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input th:value="${emp!=null}?${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}" name="birth"
type="text"
class="form-control"
placeholder="yyyy-MM-dd">
</div>
<button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button>
</form>
</div>
</main>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js"
th:src="@{/asserts/js/jquery-3.2.1.slim.min.js}"></script>
<script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/asserts/js/popper.min.js}"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{asserts/js/bootstrap.min.js/}"></script>
<!-- Icons -->
<script type="text/javascript" src="asserts/js/feather.min.js" th:src="@{/asserts/js/feather.min.js}"></script>
<script>
feather.replace()
</script>
<!-- Graphs -->
<script type="text/javascript" src="asserts/js/Chart.min.js" th:src="@{/asserts/js/Chart.min.js}"></script>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
datasets: [{
data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
lineTension: 0,
backgroundColor: 'transparent',
borderColor: '#007bff',
borderWidth: 4,
pointBackgroundColor: '#007bff'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false,
}
}
});
</script>
</body>
</html>
6.8 crud-员工删除
- 示例
<form action="subsccribe.html" th:attr="action=@{/subscribe}">
<inplut type="text" name="email"/>
<inplut type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
</form>
- 代码
<!--这样写页面表单显示别扭 【升级】-->
<!--<form th:action="@{/emp/}+${emp.id}" method="post">
<input type="hidden" name="_method" value="delete">
<button class="btn btn-sm btn-danger" type="submit">删除</button>
</form>-->
<!--【升级】-->
<button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除
</button>
<script>
$(".deleteBtn").click(function () {
//删除当前员工
let attr = $(this).attr("del_uri"); //获取当前自定义属性名值
$("#deleteEmpForm").attr("action", attr).submit();
})
</script>
7. 错误处理机制
7.1 spring boot默认的错误处理机制
-
默认效果
- 【浏览器】返回一个默认的错误页面
浏览器发送的请求的请求头
- 如果是其他客户端,默认响应一个 json数据
- 【浏览器】返回一个默认的错误页面
-
原理:可以参照
ErrorMvcAutoConfiguration
,错误处理的自动配置
DefaultErrorAttributes
帮我们在页面共享信息 【timestamp、status、error、exception、message、errors】
@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 处理默认的 /error 请求
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController
//这个方法是自适应的 既可以处理 html和json
@RequestMapping(produces = "text/html") 产生 html类型的数据;浏览器发送的请求来到这个方法处理
public ModelAndView errorHtml(
HttpServletRequest request,
HttpServletResponse response) {
//获取请求中的状态码
HttpStatus status = this.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);
}
//获取请求中的状态码
protected HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
} else {
try {
return HttpStatus.valueOf(statusCode);
} catch (Exception var4) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
}
@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);
}
//resolveErrorView 包含的内容【响应的页面】,去哪个页面是由 DefaultErrorViewResolver解析得到的。
protected ModelAndView resolveErrorView(HttpServletRequest request,
HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
//得到所有的 ModelAndView 异常视图解析器得到 modelAndView
for (ErrorViewResolver resolver : this.errorViewResolvers) {
ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
if (modelAndView != null) {
return modelAndView;
}
}
return null;
}
ErrorPageCustomizer 错误的定制页面
@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
ErrorPage errorPage = new ErrorPage(this.properties.getServletPrefix()
+ this.properties.getError().getPath());
errorPageRegistry.addErrorPages(errorPage);
}
@Value("${error.path:/error}")
private String path = "/error"; 系统出现错误以后来到 error请求处理【web.xml注册的错误页面规则】
DefaultErrorViewResolver 客户端 4xx错误,服务端 5xx
@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);
}
//模板引擎不可以的情况下调用这个方法,
return resolveResource(errorViewName, model);
}
private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
for (String location : this.resourceProperties.getStaticLocations()) {
//在静态资源资源文件下找 errorViewName对应的页面 error/404.html
try {
Resource resource = this.applicationContext.getResource(location);
resource = resource.createRelative(viewName + ".html");
//如果静态资源有东西就返回这个否则返回null
if (resource.exists()) {
return new ModelAndView(new HtmlResourceView(resource), model);
}
}
catch (Exception ex) {
}
}
return null;
}
//错误页面可以获得的数据
@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;
}
步骤:
1. 一但系统出现 4xx或者 5xx之类的错误,ErrorPageCustomizer就会生效(定制错误的响应规则), 就会来到 /error 请求;就会被 BasicErrorController处理。
2. 响应页面;去哪个页面是由 DefaultErrorViewResolver 解析得到的
7.2 如果定制错误响应
一. 如何定制错误页面
- 有模板引擎的情况下:error/状态码;【将错误的页面命名为 错误状态码.html 放在模板引擎下的 error文件夹下】,发生此状态码的错误就会来到对应的页面。
我们可用使用 4xx和 5xx作为此错误页面的文件名来匹配这种类型的所有错误,精确优先【优先寻找精确的状态码.html】
页面能获取的信息:- timestamp:时间戳
- status:状态码
- error:错误提示
- exception:异常消息
- message:异常信息
- errors: jsr303 数据校验的错误都在这里
- 没有模板引擎(模板引擎找不到这个错误页面),静态资源(resources/static)文件夹下找
- 以上都没有错误页面,就是默认来到 spring boot默认的错误提示页面
二. 如何定制错误的 json数据
- 自定义异常处理与返回定制 json数据
/** * @create 2021-10-30 22:00 * 自定义异常处理器 */ @ControllerAdvice public class MyExceptionHandler { //浏览器客户端返回的都是 json数据 @ResponseBody @ExceptionHandler(UserNotExistException.class) public Map<String, Object> handleException(Exception e) { HashMap<String, Object> map = new HashMap<>(); map.put("code", "user.notexist"); map.put("message", e.getMessage()); return map; } } //没有自适应效果。。。
- 转发到 error进行自适应效果处理
/** * @author shkstart * @create 2021-10-30 22:00 * 自定义异常处理器 */ @ControllerAdvice public class MyExceptionHandler { @ExceptionHandler(UserNotExistException.class) public String handleException(Exception e, HttpServletRequest request) { HashMap<String, Object> map = new HashMap<>(); //传入自己的状态码 4xx 5xx,否则就不会进入定制的错误页面的解析流程 /* * BasicErrorController.errorHtml() (返回ModelAndView)方法调用了 * AbstractErrorController.getStatus() 方法获取 HttpStatus。 * 我们可以自定义来定义 status_code变量并返回 * * Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code"); * */ request.setAttribute("javax.servlet.error.status_code", 420); map.put("code", "user.notexist"); map.put("message", e.getMessage()); //把我们定义的其他信息放进 request域中,在我们自定义的 ErrorAttribute进加入 request.setAttribute("ext", map); return "forward:/error"; } }
三.将我们定制数据携带出去
- 出现错误以后,会来到 /error 请去,会被
BasicErrorController
处理,响应出去可以获取的数据是由 getErrorAttribute得到的(是AbstractErrorController
(BasicErrorController的父类)【ErrorController】规定的方法
BasicErrorController extends AbstractErrorController
AbstractErrorController implements ErrorController
ErrorMvcAutoConfiguration 类中
@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
this.errorViewResolvers);
}
@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes();
}
- 完全来编写一个 ErrorController的实现类,【或者编写 AbstractErrorController的子类】放在容器中
- 页面上能用的数据,或者是 json返回能用的数据都是通过 errorAttributes.getErrorAttributes 得到。
容器中 DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的。
所以我们自定义 ErrorAttributes 继承DefaultErrorAttributes重写 getErrorAttributes()方法。/** * @author shkstart * @create 2021-10-31 17:21 * 给容器中加入我们字节的ErrorAttributes */ @Component public class MyErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) { Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace); //给容器中添加自定义的数据:公司表示 map.put("company", "cainiao"); return map; } }
- 最终的效果:响应是自适应的,可以通过定制 ErrorAttributes改变需要返回的内容。
8. 配置嵌入式 servlet容器
- SpringBoot默认使用 Tomcat作为嵌入式的 Servlet容器
- 问题?
8.1 如何定制和修改 servlet容器的相关配置
- 如何定制和修改 Servlet容器的相关配置
- 修改和 server有相关的配置【
ServerProperties
也是 implement EmbeddedServletContainerCustomizer】server.prot=8081 server.context-path=/crud server.tomcat.uri-encoding=utf-8 #通用的 servlet容器设置 server.xxx #tomcat的设置 server.tomcat.xxx
- 编写一个 EmbeddedServletContainerCustomizer:嵌入式的 servlet容器定制器,来修改Servlet容器的配置
@Bean public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer() { //定制嵌入式的 servlet容器相关的规则 return new EmbeddedServletContainerCustomizer() { @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(8083); } }; }
- 修改和 server有相关的配置【
8.2 注册 servlet三大组件【servlet,filter,listener】
- 参考1 参考2
- 由于 springboot默认是以 jar包的方式启动嵌入式的 servlet容器来启动 spring boot的文本应用,没有 web.xml文件
- 注册三大组件使用 注解方式 @ServletComponentScan("包名路径")
- 注册三大组件用以下方式配置类方法
- ServletRegistrationBean
@Bean public ServletRegistrationBean myServlet() { ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet"); registrationBean.setLoadOnStartup(1); return registrationBean; }
- FilterRegistrationBean
@Bean public FilterRegistrationBean myFilter() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new MyFilter()); registrationBean.setUrlPatterns(Arrays.asList("/hello", "/myServlet")); return registrationBean; }
- ServletListenerRegistrationBean
@Bean public ServletListenerRegistrationBean myListener() { return new ServletListenerRegistrationBean<MyListener>(new MyListener()); }
- ServletRegistrationBean
- spring boot帮我们自动配置 springmvc的时候,自动的注册 springmvc的的前端控制器;DispatcherServlet
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) public ServletRegistrationBean dispatcherServletRegistration( DispatcherServlet dispatcherServlet) { ServletRegistrationBean registration = new ServletRegistrationBean( dispatcherServlet, this.serverProperties.getServletMapping()); //默认拦截 / 所有请求;包括静态资源,但是不会拦截 jsp请求, /* 会拦截 jsp //可以通过 server.servletPath来修改 springmvc前端控制器默认拦截的请求路径 registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); registration.setLoadOnStartup( this.webMvcProperties.getServlet().getLoadOnStartup()); if (this.multipartConfig != null) { registration.setMultipartConfig(this.multipartConfig); } return registration; }
8.3 替换为其他嵌入式 servlet容器
- 默认支持:tomcat(默认) , jetty(长连接 web聊天) , undertow(不支持jsp,并发性能好)
<!--引入web模块 spring-boot-starter :springboot场景启动器,帮我们导入了web模块正常运行所依赖的 jar包--> <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容器 jetty--> <dependency> <artifactId>spring-boot-starter-jetty</artifactId> <groupId>org.springframework.boot</groupId> </dependency>
8.4 嵌入式 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依赖
//判断当前容器没有用户直接定义 EmbeddedServletContainerFactory;嵌入式的 servlet容器工厂,作用:创建嵌入式的 servlet容器
@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)//
public static class EmbeddedTomcat {
@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
return new TomcatEmbeddedServletContainerFactory();
}
}
}
#EmbeddedServletContainerAutoConfiguration 类中 原理
/**
* Nested configuration if Tomcat is being used.
*/
@Configuration
@ConditionalOnClass({ Servlet.class, Tomcat.class })
@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
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... initializers);
}
2. EmbeddedServletContainer 嵌入式的 servlet容器
3. 以 TomcatEmbeddedServletContainerFactory tomcat工厂类中的这个重写的方法
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(
ServletContextInitializer... initializers) {
// 创建一个 tomcat
Tomcat tomcat = new Tomcat();
// 配置 tomcat的基本环节
File baseDir = (this.baseDirectory != null ? this.baseDirectory
: createTempDir("tomcat"));
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
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);
// 将配置好的 tomcat传入进去,返回一个 EmbeddedServletContainer;并且启动 tomcat服务器
return getTomcatEmbeddedServletContainer(tomcat);
}
- 我们对嵌入式容器的配置修改是怎么生效的?
# application.properties 文件
ServerProperties 该文件、EmbeddedServletContainerCustomizer 嵌入式ServletContainer编辑器
EmbeddedServletContainerCustomizer:定制器帮我们修改了 servlet容器的配置?怎么修改?
5. 容器中导入了 EmbeddedServletContainerCustomizerBeanPostProcessor
EmbeddedServletContainerCustomizerBeanPostProcessor 类中
//初始化之前
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
//如果当初初始化的是一个 ConfigurableEmbeddedServletContainer类型组件
//就调该方法
if (bean instanceof ConfigurableEmbeddedServletContainer) {
postProcessBeforeInitialization((ConfigurableEmbeddedServletContainer) bean);
}
return bean;
}
private void postProcessBeforeInitialization(
ConfigurableEmbeddedServletContainer bean) {
//获取所有的定制器,调用每一个定制器的 customize方法
//给每一个属性赋值(端口号、访问路径)
for (EmbeddedServletContainerCustomizer customizer : getCustomizers()) {
//getCustomizers 拿到所有的定制器
customizer.customize(bean);
}
}
private Collection<EmbeddedServletContainerCustomizer> getCustomizers() {
if (this.customizers == null) {
// Look up does not include the parent context
//从 ioc容器中获取嵌入式容器的组件
this.customizers = new ArrayList<EmbeddedServletContainerCustomizer>(
this.beanFactory
//从容器中获取所有该类型的组件
//EmbeddedServletContainerCustomizer
//定制 servlet容器,给容器中添加一个
//EmbeddedServletContainerCustomizer类型的组件
.getBeansOfType(EmbeddedServletContainerCustomizer.class,
false, false)
.values());
Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE);
this.customizers = Collections.unmodifiableList(this.customizers);
}
return this.customizers;
}
//ServerProperties 也是定制器
总结
- springboot根据导入的依赖情况,给容器中添加响应的 EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactory】
- 容器中某个组件要创建对象就会惊动后置处理器;
EmbeddedServletContainerCustomizerBeanPostProcessor
只要是嵌入式的 Servlet容器工厂,后置处理处理器就可以工作了 - 后置处理器,从容器中获取所有的 EmbeddedServletContainerCustomizer(嵌入式servlet容器定制器)调用定制器的定制方法。
8.5 嵌入式 servlet容器启动原理
- 声明时候创建嵌入式的 Servlet容器工厂?什么时候获取嵌入式的 Servlet容器并启动 Tocmat
-
获取 spring boot应用启动运行 run()方法
-
refreshContext(context); spring boot属性 ioc容器【创建 ioc容器对象并初始化容器中的每一个组件】
如果是 web应用创建:AnnotationConfigEmbeddedWebApplicationContext,否则:AnnotationConfigApplicationContext
-
refresh(context); 刷新刚才创建号的 ioc容器
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
-
onRefresh(); web的ioc容器 重写 onRefresh()方法
-
web ioc容器会创建嵌入式的 servlet容器:createEmbeddedServletContainer();
-
获取嵌入式的 servlet容器工厂:
EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
从 ioc容器中获取 EmbeddedServletContainerFactory组件
TomcatEmbeddedServletContainerFactory 创建对象,惊动了后置处理器,后置处理器获取所有的定制器对象来获取定制 servlet容器的相关配置。 -
使用容器工程获取嵌入式的 servlet容器
this.embeddedServletContainer = containerFactory
.getEmbeddedServletContainer(getSelfInitializer()); -
嵌入式的 servlet容器创建对象并启动 servlet容器
先启动嵌入式的 servlet容器,在将 ioc容器中剩下没有创建出的对象获取出来。
ioc容器启动创建嵌入式的 servlet容器
9. 使用外置的 servlet容器
- 嵌入式 servlet容器
优点:简单,便携
缺点:默认不支持 jsp,优化定制比较复杂【使用定制器 ServerProperties,自定义 EmbeddedServletContainerCustomizer】,自己编写 servlet容器工厂【EmbeddedServletContainerFacotry】 - 外置的 servlet容器:外面安装 tomcat--应用war包的方式打包。
9.1 步骤
- 必须创建一个 war项目
- 将嵌入式的 tomcat指定为 provided
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>
- 必须编写一个 SpringBootServletInitializer 的子类,并调用 configure方法
public class ServletInitializer extends SpringBootServletInitializer{ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application){ //传入spring boot主程序 return application.sources(SpringBoot04WebJspApplication.class); } }
- 启动服务器就可以使用了
9.2 原理
jar包:执行 SpringBoot 主内的 main方法,启动 ioc容器,创建嵌入式的 servlet容器
war包:启动服务器,服务器启动 springboot应用,启动ioc容器。
- 在 servlet3.0 的时候定义了一个规范
在 servlet3.0 pdf文件中的 8.2.4 章节 Shared libraries / runtimes pluggability
规则:- 服务器【web应用启动】会创建当前 web应用里面每一个 jar包里面 ServletContainerinitializer实例
- ServletContainerinitializer 的实现的 jar包妨碍 META-INF/services文件夹下,有一个名为 javax.servlet.ServletContainerInitializer,内容就是 ServletContainerinitializer的实现类的全类名。
- 还可以使用 @HandlesTypes 注解,作用就是:在应用启动的时候加载我们感性的类。
流程
-
启动 tomcat
-
在 spring的 web模块里面有这个文件
spring-web-4.3.13.RELEASE.jar!\META-INF\services\javax.servlet.ServletContainerInitializer
-
SpringServletContainerInitializer 将 @HandlesTypes(WebApplicationInitializer.class)这个类型的类传入到 onStartup方法的 Set《Class《?》》为这些 WebApplicationInitializer类型的类创建对象,
-
每一个 WebApplicationInitializer都调用直接的 onStartup方法
-
相当于我们的 SpringBootServletInitializer的类会被创建对象,并执行 onStartup方法并执行
-
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方法,子类重写了这个方法,传入spring boot主类的主程序 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 return run(application); }
-
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. 项目使用 jsp页面
10.1 pom
<!-- 添加servlet依赖模块 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- 添加jstl标签库依赖模块 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--添加tomcat依赖模块.-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
10.2 项目添加 web模块
- 快捷键:Ctrl + Shift + Alt + S 打开 Project structure(项目模块)
10.3 配置文件
# 视图解析器的前缀
spring.mvc.view.prefix=/
# 视图解析器的后缀
spring.mvc.view.suffix=.jsp
10.4 项目启动
a 修改环境启动
- $MODULE_WORKING_DIR$
- 启动 主程序
b maven 插件启动
- 插件启动不需要配置