1.web创建
使用SpringBoot:
1.创建SpringBoot应用,选择需要的模块
2.SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3.编写业务代码
自动配置原理
每个场景SpringBoot帮我们配置了什么,能不能修改
xxxxAutoConfiguration:帮我们给容器中自动配置组件
xxxxProperties:配置类来封装配置文件的内容
2.静态资源映射规则
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware, InitializingBean {
//可以设置和静态资源有关的参数
WebMvcAutoConfiguration类
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(cachePeriod));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(
registry.addResourceHandler(staticPathPattern)
.addResourceLocations(
this.resourceProperties.getStaticLocations())
.setCachePeriod(cachePeriod));
}
}
//欢迎页映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {
return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern());}
//图标映射
@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(Ordered.HIGHEST_PRECEDENCE + 1);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler
.setLocations(this.resourceProperties.getFaviconLocations());
return requestHandler;
}
}
1.所有/webjars/**,都去classpath:classpath:/META-INF/resources/webjars/
webjars:以jar包方式引入静态资源;
<!-- 引入webjars-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
2.“/**”访问当前项目的任何资源(静态资源文件夹)
resources 下是类路径classpath
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/"
3.欢迎页:静态文件夹下所有index.html —>映射为"/**"
4.图标映射:所有的**/favicon.ico 都是在静态资源文件下找;
3.模板引擎
jsp Velocity Freemarker Thymeleaf
SpringBoot推荐的Thymeleaf;
语法简单,功能强大;
1.引入Thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
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页面放在classpath:/templates/ ,thymeleaf就能自动渲染;
1.导入thymeleaf名称空间
xmlns:th="http://www.thymeleaf.org"
2.thymeleaf语法规则
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功</h1>
<div th:text="${hello }">这是欢迎信息</div>
</body>
3.语法规则
a. th:text 改变当前元素里面的文本内容
th 任意属性替换原生属性 th:id="${}"
[外链图片转存失败(img-Br3V5Q5L-1564008788250)(C:\Users\Administrator\Desktop\GitHub\spring-boot\assets\1563967235138.png)]
b.表达式语法
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.
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使用
<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: _ (无操作)
行内写法:[[ session.user.name]]−−−>th:text="{session.user.name}"
4.SpringMvc自动配置
1.SpringMvc自动配置
以下是SpringBoot对springmvc的默认:
- Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.- 自动配置了 视图解析器(根据方法返回值,返回view,视图对象决定如何渲染)
- ContentNegotiatingViewResolver组合所有的视图解析器
- Support for serving static resources, including support for WebJars (see below).
- 静态资源文件夹路径和webjars
- Automatic registration of
Converter
,GenericConverter
,Formatter
beans.- 自动注册 :类型转换、格式化器数据
- Support for
HttpMessageConverters
(see below).- 用来转换http请求和响应 user–json
- Automatic registration of
MessageCodesResolver
(see below).- 定义错误代码生成规则
- Static
index.html
support.- 静态首页访问
- Custom
Favicon
support (see below).- 图标
- Automatic use of a
ConfigurableWebBindingInitializer
bean (see below).- 请求数据绑定到javabean;数据绑定器;
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration
class of type WebMvcConfigurerAdapter
, but without @EnableWebMvc
. If you wish to provide custom instances of RequestMappingHandlerMapping
, RequestMappingHandlerAdapter
or ExceptionHandlerExceptionResolver
you can declare a WebMvcRegistrationsAdapter
instance providing such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration
annotated with @EnableWebMvc
.
2.扩展SpringMvc
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc
既保留了所有的自动配置,也能使用我们扩展的配置
//使用WebMvcConfigurerAdapter可以来扩展SpringMvc功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/atguigu").setViewName("success");
}
}
原理:
1.WebMVCAutoConfiguration是SpringMvc的自动配置类
2.在做其他自动配置时会导入;@import(EnableWebMvcConfiguation.class)
@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相关的配置一起调用;
}
}
3.所有容器中webConfig一起起作用
4.我们的配置类一起被调用;
3.全面接管SpringMvc
@EnableWebMvc最原始的框架,全部由自己配置
5.如何修改SpringBoot默认配置
模式:
1.SpringBoot自动配置很多组件时候,先看容器中有没有用户自己配置的(@Bean @Component)如果有就用用户的配置,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
2.在SpringBoot中会有非常多的xxxConfiguration