版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kaikai_sk/article/details/85019088
1. 简介
使用springboot
- 创建SpringBoot应用,选中相应的模块
- SpringBoot已经将场景配置好了,我们需要修改少量的配置
- 编写业务代码
自动配置原理
xxxAutoConfiguration:自动给容器中配置组件
xxxProperties:配置类,用来封装配置文件的内容
2. SpringBoot对静态资源的映射规则
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
//这个类用来设置和静态资源有关的参数,例如缓存时间等
public class ResourceProperties implements ResourceLoaderAware {}
public class WebMvcAutoConfiguration {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Integer cachePeriod = this.resourceProperties.getCachePeriod();
// webjar的目录和之前的web开发的目录一致
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));
}
}
//配置欢迎页
@Bean
public WebMvcAutoConfiguration.WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {
return new WebMvcAutoConfiguration.WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
}
//配置喜欢的图标
@Configuration
@ConditionalOnProperty(
value = {"spring.mvc.favicon.enabled"},
matchIfMissing = true
)
public static class FaviconConfiguration {
private final ResourceProperties resourceProperties;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
//所有的 **/favicon.ico
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler.setLocations(this.resourceProperties.getFaviconLocations());
return requestHandler;
}
}
}
2.1 webjars
去 classpath:/META-INF/resources/webjars/找资源
<!--引入jquery-webjar 在访问的时候只需要写webjars下的资源名称即可-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
2.2 /**
private static final String[] SERVLET_RESOURCE_LOCATIONS = new String[]{"/"};
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"};
所以说,访问当前项目的任何资源,都去(静态资源文件夹)下面去找映射
/
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
2.3 欢迎页
private WelcomePageHandlerMapping(Resource welcomePage, String staticPathPattern) {
if (welcomePage != null && "/**".equals(staticPathPattern)) {
logger.info("Adding welcome page: " + welcomePage);
ParameterizableViewController controller = new ParameterizableViewController();
controller.setViewName("forward:index.html");
this.setRootHandler(controller);
this.setOrder(0);
}
}
所有静态资源文件夹下的index.html文件
2.4 icon
还是在静态资源文件夹下找
3. 模板引擎
就是模板+数据,比如jsp
SpringBoot推荐使用ThymeLeaf:语法更简单,功能更强大
3.1 引入ThymeLeaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
切换版本
<properties>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<!-- thymeleaf2 layout1-->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
3.2 使用ThymeLeaf
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
只要我们把html页面放在classpath:/templates/下,thymeleaf就能够自动渲染
- 导入名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
- 使用thymeleaf语法
<!--th:text 将div里面的文本内容设置为 -->
<div id="div01" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">这是显示欢迎信息</div>
<hr/>
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<hr/>
SpringMVC自动配置
4.1 SpringMVC的自动配置
-
Inclusion of BeanNameViewResolver 和 ContentNegotiatingViewResolver beans
- 自动配置了ViewResolver(视图解析器)
视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?) - ContentNegotiatingViewResolver:组合所有的视图解析器
- 如何定制一个自己的视图解析器:可以自己给容器中添加一个视图解析器,自动将其组合进来。
- 自动配置了ViewResolver(视图解析器)
-
支持静态资源服务
- webjars
- 静态资源文件夹路径
- 静态首页访问(index.html)
- 自定义的icon (favicon.ico)
-
自动注册了Converter,GenericConverter和Formatter
- Converter:转换器,数据类型转换
- Formatter:格式化器。日期时间类型的转换
@Bean @ConditionalOnProperty( prefix = "spring.mvc", //在配置文件中配置了日期格式化的规则 name = {"date-format"} ) public Formatter<Date> dateFormatter() { //日期格式化的组件 return new DateFormatter(this.mvcProperties.getDateFormat()); }
自己添加的Converter或者Formatter,只要添加到容器中即可
- HttpMessageConverter: 转换Http请求和响应:对象–Json
HttpMessageConverter是从容器中确定的,获取所有的HttpMessageConverter。同理自定义的HttpMessageConverter只需要注入到容器中即可
-
MessageCodesResolver
定义错误代码生成规则 -
ConfigurableWebBindingInitializer
ConfigurableWebBindingInitializer可以自定义,添加到IOC中即可
初始化WebDataBinder
请求数据<---->Java Bean
org.springframework.boot.autoconfigure.web: web下所有的自动配置场景
4.2 如何修改SpringBoot的默认配置
- SpringBoot在配置组件的时候先看有没有用户定义的,如果有使用用户配置的,没有就使用自动生成的
如果组件可以有多个,将用户配置的和默认的组合使用