springboot与web开发
1 创建springboot’项目,选择需要的模块,如redis,mybatis等
2 与ssm不同,spring已经将大部分配置都配置好,只需要再根据需求配置少量的个性化配置即可。可以配置哪些属性,可以在XXautoconfigration中XXXproperties找到。
3 编写业务代码
**一 springboot 静态资源的映射规则:
**
1 webmvcautoconfigration中的addresourcehandler中规定了位置
所有
"/webjars/*" ,都去classpath:META-INF/resources/webjars/找资源;
webjars:以jar包的方式引入静态资源 官网 http://www.webjars.org/
"/**" 去 classpath:/META-INF/resources/
classpath:/resources/*
classpath:/static/*
classpath:/public/*
其中类路径根路径为java或resources
而
二 模版引擎 thymeleaf
1 什么是模版引擎
如图,模版引擎在web中可以简单理解为对modelview中的对象自动调用,方便前后端隔离。常见的有thymeleaf,freemarker等
springboot推荐使用thymeleaf;
1 引入thymeleaf;导入相应的starter 如果不适用springboot中设置好的版本,可以去github上找到想用的版本,注意:修改版本需要重写thymeleaf version以及layout version两者需对应,如layout2对应thymeleaf3
2
如图相应配置文件同样在thymeleafautoconfigration中的thtmeleafproperties,根据最后两行的视图解析器配置,只要把.html页面放在classpath:/templates中就可以自动渲染了
使用thymeleaf:
第一步 导入thymeleaf的名称空间
第二部 语法
上图来自官方文档第十章
2 表达式 官方文档 第四章
三 springmvc自动配置原理
1 ContentNegotiatingViewResolver 内容协商视图解析器
自动配置了ViewResolver,就是我们之前学习的SpringMVC的视图解析器;
即根据方法的返回值取得视图对象(View),然后由视图对象决定如何渲染(转发,重定向)。
源码:找到 WebMvcAutoConfiguration , 搜索ContentNegotiatingViewResolver。
@Bean
@ConditionalOnBean(ViewResolver.class)
@ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)
public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class))
// ContentNegotiatingViewResolver使用所有其他视图解析器来定位视图,因此它应该具有较高的优先级
resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
return resolver;
}
ContentNegotiatingViewResolver 这个视图解析器就是用来组合所有的视图解析器的
自己实现一个视图解析器:
@Bean //放到bean中
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
//写一个静态内部类,视图解析器就需要实现ViewResolver接口
private static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
转换器和格式化器
converter 转换器 类型转换使用
Formatter 格式化器 例如 2020.5.1==Date;
自己也可添加格式化器或者转换器,同样放到容器中即可
总结一:SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(如果用户自己配置@bean),如果有就用用户配置的,如果没有就用自动配置的;
如果有些组件可以存在多个,比如我们的视图解析器,就将用户配置的和自己默认的组合起来!
扩展使用springmvc
要做的就是编写一个@Configuration注解类,并且类型要为WebMvcConfigurer,还不能标注@EnableWebMvc注解;
举例:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 浏览器发送/test , 就会跳转到test页面;
registry.addViewController("/test").setViewName("test");
}
}
全面接管SpringMVC
全面接管即:SpringBoot对SpringMVC的自动配置不需要了,所有都是自己去配置!
方法:在配置类中添加@EnableWebMvc即可;
原理:@EnableWebMvc将WebMvcConfigurationSupport组件导入进来了;
而导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能!