SpringBoot学习笔记03
1.Thymeleaf模板引擎
1.1 模板引擎
前端交给我们的页面,是html页面,如果以前开发,我们需要把它转成jsp页面,jsp的好处是当我们查出一些数据转发到jsp页面以后,我们可以用jsp轻松实现数据的显示,及交互等
jsp支持非常强大的功能,包括能写java代码,但是使用springboot创建的项目,是以jar的方式,不是war,而且用的是嵌入式的Tomcat,所以默认是不支持jsp的
不支持jsp,如果我们直接用静态页面的方式,会给开发带来非常大的麻烦
这时,SpringBoot推荐你可以来使用模板引擎
模板引擎,其实之前接触到了很多,其中jsp就是一个模板引擎,还有用的比较多的freemarker,包括springboot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的
模板引擎的作用就是我们来写一个页面模板,比如一些值,是动态的,我们写一些表达式,而这些值,从哪儿来呢,就是我们在后台封装一些数据,然后把这个模板和这个数据交给我们的模板引擎,模板引擎按照我们这个数据帮你把这个表达式解析,填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写进去,这就是我们这个模板引擎,不管是jsp还是其他的模板引擎,都是这个思想,只不过不同的模板引擎之间的语法可能不一样
1.2 引入Thymeleaf
对于springboot来说,就是一个start的事情
Thymeleaf 官网:https://www.thymeleaf.org/
Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf
Spring官方文档:找到我们对应的版本
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter
找到对应的pom依赖
<!--thymeleaf--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
添加到pom.xml文件中,maven会自动下载相关的jar包

1.3 Thymeleaf分析
既然已经引入了Thymeleaf,那么要怎么使用呢?
首先得按照springboot的自动配置原理看一下我们这个Thymeleaf的自动配置规则,在按照那个规则进行使用
去找一下Thymeleaf的自动配置类:ThymeleafProperties
@ConfigurationProperties(prefix = "spring.thymeleaf")public class ThymeleafProperties {private static final Charset DEFAULT_ENCODING;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";private String mode = "HTML";private Charset encoding;}
我们可以在其中看到默认的前缀和后缀
我们只需要把我们的html页面放在类路径下的templates下,Thymeleaf就可以帮我们自动渲染
使用Thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可
测试
- 编写一个Controller
@Controllerpublic class HelloController {@RequestMapping("/test")public String hello(){return "test";}}
- 编写一个测试页面test.html 放在templates目录下
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><h1>测试页面</h1></body></html>
- 启动项目请求测试

1.4 Thymeleaf语法学习
做个简单的练习:我们需要查出一些数据,在页面中展示
- 修改测试请求,增加数据传输
@RequestMapping("/t1")public String test1(Model model){//存入数据model.addAttribute("msg","Hello,Thymeleaf");return "test";}
- 我们要使用thymeleaf,需要在html文件中导入命名空间的约束,方便提示
xmlns:th="http://www.thymeleaf.org"
- 去编写下前端页面
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Title</title></head><body><h1>测试页面</h1><!--th:text就是将div中的内容设置为他指定的值--><div th:text="${msg}"></div></body></html>
- 启动测试

练习测试
- 编写一个Controller,放一些数据
@RequestMapping("/t2")public String test2(Map<String,Object> map){//存入数据map.put("msg","<h1>Hello</h1>");map.put("users", Arrays.asList("jcsune","test"));return "test";}
- 测试页面取出数据
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Title</title></head><body><h1>测试页面</h1><!--th:text就是将div中的内容设置为他指定的值--><div th:text="${msg}"></div><!--不转义--><div th:utext="${msg}"></div><!--遍历数据--><!--th:each 每次遍历都会生成当前这个标签--><h4 th:each="user :${users}" th:text="${user}"></h4><h4><!--行内写法:官网#12--><span th:each="user:${users}">[[${user}]]</span></h4></body></html>
- 启动测试

2.MVC自动配置原理
2.1 官网阅读
在进行项目编写前,我们还需要了解一个东西,就是SpringBoot对我们的SpringMVC还做了哪些配置,包括如何扩展,如何定制
途径一:源码分析
途径二:官方文档
Spring MVC Auto-configuration// Spring Boot为Spring MVC提供了自动配置,它可以很好地与大多数应用程序一起工作。Spring Boot provides auto-configuration for Spring MVC that works well with most applications.// 自动配置在Spring默认设置的基础上添加了以下功能:The auto-configuration adds the following features on top of Spring’s defaults:// 包含视图解析器Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.// 支持静态资源文件夹的路径,以及webjarsSupport for serving static resources, including support for WebJars// 自动注册了Converter:// 转换器,这就是我们网页提交数据到后台自动封装成为对象的东西,比如把"1"字符串自动转换为int类型// Formatter:【格式化器,比如页面给我们了一个2019-8-10,它会给我们自动格式化为Date对象】Automatic registration of Converter, GenericConverter, and Formatter beans.// HttpMessageConverters// SpringMVC用来转换Http请求和响应的的,比如我们要把一个User对象转换为JSON字符串,可以去看官网文档解释;Support for HttpMessageConverters (covered later in this document).// 定义错误代码生成规则的Automatic registration of MessageCodesResolver (covered later in this document).// 首页定制Static index.html support.// 图标定制Custom Favicon support (covered later in this document).// 初始化数据绑定器:帮我们把请求数据绑定到JavaBean中!Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document)./*如果您希望保留Spring Boot MVC功能,并且希望添加其他MVC配置(拦截器、格式化程序、视图控制器和其他功能),则可以添加自己的@configuration类,类型为webmvcconfiguer,但不添加@EnableWebMvc。如果希望提供RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定义实例,则可以声明WebMVCregistrationAdapter实例来提供此类组件。*/If you want to keep Spring Boot MVC features and you want to add additional MVC configuration(interceptors, formatters, view controllers, and other features), you can add your own@Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to providecustom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, orExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.// 如果您想完全控制Spring MVC,可以添加自己的@Configuration,并用@EnableWebMvc进行注释。If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
2.2 ContentNegotiatingViewResolver 内容协商视图解析器
自动配置了ViewResolver,就是之前学习的SpringMVC的视图解析器
即根据方法的返回值取得视图对象(View),然后由视图对象决定如何渲染(转发,重定向)
去看源码,找到WebMvcAutoConfiguration,然后搜索ContentNegotiatingViewResolver 找到如下方法
public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class));// ContentNegotiatingViewResolver uses all the other view resolvers to locate// a view so it should have a high precedenceresolver.setOrder(Ordered.HIGHEST_PRECEDENCE);return resolver;}
点进ContentNegotiatingViewResolver类,找到对应的解析视图的代码
@Nullablepublic View resolveViewName(String viewName, Locale locale) throws Exception {RequestAttributes attrs = RequestContextHolder.getRequestAttributes();Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");List<MediaType> requestedMediaTypes = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest());if (requestedMediaTypes != null) {List<View> candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes);View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs);if (bestView != null) {return bestView;}}
继续点进getCandidateViews方法,看到他是把所有的视图解析器拿来,进行while循环,挨个解析
private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes) throws Exception {List<View> candidateViews = new ArrayList();if (this.viewResolvers != null) {Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set");Iterator var5 = this.viewResolvers.iterator();while(var5.hasNext()) {ViewResolver viewResolver = (ViewResolver)var5.next();View view = viewResolver.resolveViewName(viewName, locale);if (view != null) {candidateViews.add(view);}
所以得出结论 ContentNegotiatingViewResolver这个视图解析器就是用来组合所有的视图解析器的
我们再去研究下他的组合逻辑,看到一个属性viewResolvers,看看它是在哪里进行赋值的
protected void initServletContext(ServletContext servletContext) {// 这里它是从beanFactory工具中获取容器中的所有视图解析器// ViewRescolver.class 把所有的视图解析器来组合的Collection<ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.obtainApplicationContext(), ViewResolver.class).values();ViewResolver viewResolver;if (this.viewResolvers == null) {this.viewResolvers = new ArrayList(matchingBeans.size());Iterator var3 = matchingBeans.iterator();while(var3.hasNext()) {viewResolver = (ViewResolver)var3.next();if (this != viewResolver) {this.viewResolvers.add(viewResolver);}}} else {for(int i = 0; i < this.viewResolvers.size(); ++i) {viewResolver = (ViewResolver)this.viewResolvers.get(i);if (!matchingBeans.contains(viewResolver)) {String name = viewResolver.getClass().getName() + i;this.obtainApplicationContext().getAutowireCapableBeanFactory().initializeBean(viewResolver, name);}}}AnnotationAwareOrderComparator.sort(this.viewResolvers);this.cnmFactoryBean.setServletContext(servletContext);}
可以看出它是在容器中去找视图解析器,这样的话我们是否可以自己实现一个视图解析器呢
我们可以自己给容器中添加视图解析器,这个类就会帮我们自动的将他组合起来
- 我们在主程序中去写一个视图解析器来试试
public class MyMvcConfig implements WebMvcConfigurer {@Bean //放到bean中public ViewResolver myViewResolver(){return new MyViewResolver();}//自定义了一个自己的视图解析器private static class MyViewResolver implements ViewResolver {@Overridepublic View resolveViewName(String s, Locale locale) throws Exception {return null;}}}
- 怎么看我们的视图解析器有没有起作用
我们给 DispatcherServlet 中的 doDispatch方法 加个断点进行调试一下,因为所有的请求都会走到这个方法中

- 启动项目,随便访问一个页面,看一下debug信息,找到this

- 找到视图解析器看到我们自定义的就在这里

所以说,我们如果想要使用自己定制化的东西,我们只需要给容器中添加这个组件就行了,剩下的事情SpringBoot就会帮我们做了
2.3 修改springboot的默认配置
这么多的自动配置,原理都是一样的,通过这个webmvc的自动配置原理分析,我们要学会一种学习方式,通过源码探究,得出结论,这个结论一定是属于自己的而且一通百通
springboot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(用户自己配置的bean),如果有就用用户配置的,如果没有就用自动配置的
扩展使用SpringMVC,官方文档如下:
f you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
我们要做的就是编写一个@Configuration注解类,并且类型要为WebMvcConfigurer,还不能标注@EnableWebMvc注解,我们自己去写一个;我们新建一个包叫config,写一个类MyMvcConfig
//应为类型要求为WebMvcConfigurer,所以我们实现其接口//可以使用自定义类扩展MVC的功能@Configurationpublic class MyMvcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {// 浏览器发送/test , 就会跳转到test页面;registry.addViewController("/test").setViewName("test");}}
去浏览器访问一下

可以看到,确实也跳转过来了,所以说,我们要扩展SpringMVC,官方就推荐我们这么去使用,即保留springboot所有的自动配置,也能用我们扩展的配置
接着去分析一下原理
WebMvcAutoConfiguration是springMvc的自动配置类,里面有一个类WebMvcAutoConfigurationAdapter
这个类上有一个注解,在做其他自动配置时会导入@Import(EnableWebMvcConfiguration.class)

我们点进EnableWebMvcConfiguration.class这个类看一下,它继承了一个父类 DelegatingWebMvcConfiguration
这个父类中有这样一段代码:
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);}}}
我们可以在这个类中去寻找一个我们刚才设置的viewController当做参考,发现它调用了一个
protected void addViewControllers(ViewControllerRegistry registry) {this.configurers.addViewControllers(registry);}
点进去看一下
public void addViewControllers(ViewControllerRegistry registry) {Iterator var2 = this.delegates.iterator();while(var2.hasNext()) {// 将所有的WebMvcConfigurer相关配置来一起调用!包括我们自己配置的和Spring给我们配置的WebMvcConfigurer delegate = (WebMvcConfigurer)var2.next();delegate.addViewControllers(registry);}}
所以得出结论:所有的WebMvcConfiguration都会被作用,不止Spring自己的配置类,我们自己的配置类当然也会被调用;
2.4 全面接管SpringMVC
官方文档
If you want to take complete control of Spring MVCyou can add your own @Configuration annotated with @EnableWebMvc.
全面接管即:SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己去配置,只需要我们在配置类中加一个@EnableWebMvc
我们看下如果我们全面接管了SpringMVC ,我们之前SpringBoot给我们配置的静态资源映射一定会无效,去测试一下,不加注解之前访问首页

给配置类加上注解@EnableWebMvc

可以看到所有的SpringMVC自动配置都失效了,回归到了最初的样子
实际开发中,不推荐使用全面接管SpringMVC
为什么加了一个注解,自动配置就会失效了,我们可以去看一下源码
- 点进注解,发现它是导入了一个类
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE})@Documented@Import({DelegatingWebMvcConfiguration.class})public @interface EnableWebMvc {}
- 继续点进去这个类,发现它继承了一个父类 WebMvcConfigurationSupport
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();public DelegatingWebMvcConfiguration() {}
- 回顾一下WebMvcAutoConfiguration,发现里面有这样一个注解@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@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 {public static final String DEFAULT_PREFIX = "";public static final String DEFAULT_SUFFIX....
总结:@EnableWebMvc将WebMvcConfigurationSupport组件导入进来了;由于@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)导致SpringMVC的自动配置都失效
