- 要使用SpringBoot做web开发,如果使用IDEA开发工具的话,可以在创建SpringBoot项目的时候就选择要添加的模块,这样SpringBoot会自动对项目进行配置.
- 这其中包括,基本的web应用环境,数据库链接选择,缓存选择等等.
- SpringBoot主要依靠xxxxAutoConfiguration:帮我们给容器中自动配置组件,并使用xxxxProperties:配置类来封装配置文件的内容.
SpringBoot对静态资源的访问
- 当项目中需要使用到一些公用的插件文件,例如:jQuery,bootstrap等等,在SpringBoot之中可以使用jar包的引入对应的依赖,就可以直接访问对应的文件了.
- 例如项目中需要使用jQuery文件,可以在pom.xml文件之中加入以下的依赖
<!‐‐引入jquery‐webjar‐‐>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
- 访问路径为:http://localhost:8080/webjars/jquery/3.3.1/jquery.js
- 对于所有的webjars的资源文件访问路径,SpringBoot做了相应的配置
2. 对于项目中自己的静态资源文件,SpringBoot定义了以下几个位置存放静态资源文件
"classpath:/META‐INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径
- "classpath"表示java文件的跟路径,在IDEA之中用蓝色文件夹表示,并且IDEA中"resources"也表示java文件根路径
- 示例:在"resources"下创建"static"文件夹,在"static"文件夹下放入要使用的文件
- 访问这些文件的路径为:
localhost:8080/文件夹名/文件名
- Bootstrap会自动在静态资源文件位置下寻找 对应的文件夹名称
- 例如要访问"bootstrap-solid.svg"图片,那么只需要输入路径:localhost:8080/img/bootstrap-solid.svg
- 设置欢迎页面,默认情况下SpringBoot将所有静态资源文件夹下的index.html文件设置为欢迎页面
- 示例:定义index.html页面
- 当直接访问项目根路径时,如果存在index.html文件,会自动跳转到index.html文件
- localhost:8080
- 设置浏览器图标,不同的web应用有自己的浏览器图标,例如"百度",“csdn”,“SpringBoot”
- 要替换浏览器图标,只需要在"static"静态资源文件夹中的任意一个子文件夹中加入"favicon.ico "命名的图
- 示例:加入自己的"favicon.ico"图标
- 而后在每一个页面中,加入以下代码
<link rel="icon" type="image/x-icon" href="/img/favicon.ico">
引擎模版
- 在一般开发之中,页面基本会采用*.jsp作为页面,这是因为jsp支持强大的标签库,可以做遍历,判断等操作,并且支持直接编写java代码.
- 而相对于html文件内容都是静态的,jsp这种页面可以做到动态的显示页面,类似于jsp这样的页面就称之为引擎模版.
- 引擎模版功能上大同小异,只不过语法上略有不同,都是通过在页面之中设定占位符,而后通过一些方法取得数据,最后设置占位符内容,最后输出为不同的页面显示.
-
SpringBoot推荐的Thymeleaf语法更简单,功能更强
-
要引入thymeleaf,只需要在pom.xml文件之中添加依赖即可,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐thymeleaf</artifactId>
</dependency>
- SpringBoot默认情况下使用的是2.1.6版本,要使用更高的版本,只需要在pom.xml文件中覆盖对应的版本即可
- 需要注意的是,如果要更换thymeleaf版本为3.0以上,那么需要使用的对应thymeleaf-layout-dialect要为2.0以上
<properties>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
thymeleaf基本语法
- SpringBoot中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";
- SpringBoot中要使用thymeleaf模版引擎渲染页面,只需要将html页面放到"classpath:/templates/"文件夹下即可.
- 示例:在templates文件夹下创建 "hello.html"页面
- 注意<meta>标签最好有结束符号<meta/>,否则容易出现500
- 如果pom文件中没有正确导入thymeleaf依赖,则会出现404错误
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>你好</title>
</head>
<body>
<div th:text="${hello}">这里显示"th:text"的内容</div>
</body>
</html>
- 在html页面开口部分,可以导入thymelefa的名称空间,这样在编写代码的时候会有对应的语法提示
<html lang="en" xmlns:th="http://www.thymeleaf.org">
-
其中页面中将表达式写在了div元素内部,“th:text"表示为设置元素的文本内容,”${hello}"为接收名为hello的对象.
-
这样做的好处就是,可以做到前后端分离,
-
定义后台方法
@RequestMapping("/helloHtml")
public String helloHtml(Map<String, Object> map) {
map.put("hello", "大家好");
return "hello";
}
语法规则
语法 | 作用 |
---|---|
th:text; | 改变当前元素里面的文本内容; |
th:任意html属性; | 来替换原生属性 |
SpringMVC自动配置原理(转自尚硅谷)
1. Spring MVC auto-configuration
Spring Boot 自动配置好了SpringMVC
以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration)
-
Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.- 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?))
- ContentNegotiatingViewResolver:组合所有的视图解析器的;
- 如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来;
-
Support for serving static resources, including support for WebJars (see below).静态资源文件夹路径,webjars
-
Static
index.html
support. 静态首页访问 -
Custom
Favicon
support (see below). favicon.ico
-
自动注册了 of
Converter
,GenericConverter
,Formatter
beans.- Converter:转换器; public String hello(User user):类型转换使用Converter
Formatter
格式化器; 2017.12.17===Date;
@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件中配置日期格式化的规则
public Formatter<Date> dateFormatter() {
return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化组件
}
自己添加的格式化器转换器,我们只需要放在容器中即可
-
Support for
HttpMessageConverters
(see below).-
HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User—Json;
-
HttpMessageConverters
是从容器中确定;获取所有的HttpMessageConverter;自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中(@Bean,@Component)
-
-
Automatic registration of
MessageCodesResolver
(see below).定义错误代码生成规则 -
Automatic use of a
ConfigurableWebBindingInitializer
bean (see below).我们可以配置一个ConfigurableWebBindingInitializer来替换默认的;(添加到容器)
初始化WebDataBinder; 请求数据=====JavaBean;
org.springframework.boot.autoconfigure.web:web的所有自动场景;
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
.
扩展SpringMVC于全面接管SpringMVC
- 有些时候我们需要使用SpringBoot自动配置的SpringMVC之外,需要自己扩展自己的配置,那么要在不移除自动配置的前提下,扩展自己的配置信息可以使用以下方式
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc;
既保留了所有的自动配置,也能用我们扩展的配置;
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /atguigu 请求来到 success
registry.addViewController("/atguigu").setViewName("success");
}
}
原理:
1)、WebMvcAutoConfiguration是SpringMVC的自动配置类
2)、在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)
@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
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
// public void addViewControllers(ViewControllerRegistry registry) {
// for (WebMvcConfigurer delegate : this.delegates) {
// delegate.addViewControllers(registry);
// }
}
}
}
3)、容器中所有的WebMvcConfigurer都会一起起作用;
4)、我们的配置类也会被调用;
效果:SpringMVC的自动配置和我们的扩展配置都会起作用;
3、全面接管SpringMVC;
- 一般情况下不建议这样使用
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了
我们需要在配置类中添加@EnableWebMvc即可;
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /atguigu 请求来到 success
registry.addViewController("/atguigu").setViewName("success");
}
}
原理:
为什么@EnableWebMvc自动配置就失效了;
1)@EnableWebMvc的核心
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
2)、
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
3)、
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
WebMvcConfigurerAdapter.class })
//容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
4)、@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;
5)、导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;