SpringBoot与web开发
简介
使用SpringBoot;
1)、创建SpringBoot应用,选中我们需要的模块; 比如web等等
2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3)、自己编写业务代码;
参考这里:
比如要连接数据库的:有数据库的配置
查看 @EnableConfigurationProperties中的 dataSourceProperties.class
@ConfigurationProperties(prefix = "spring.datasource") //跟配置绑定 public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
自动配置原理?
这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?xxx
xxxxAutoConfiguration:帮我们给容器中自动配置组件; xxxxProperties:配置类来封装配置文件的内容;
Web:
关于web 就是 restful的栗子了
restful web开发
Spring boot 最后打成个jar包,web开发时候,页面放哪里?
Spring boot对静态资源的映射规则
这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?xxx
xxxxAutoConfiguration:帮我们给容器中自动配置组件; xxxxProperties:配置类来封装配置文件的内容;
idea: ctrl+shift+n
这个类里面有个方法: 添加资源映射
public void addResourceHandlers(ResourceHandlerRegistry registry) {if (!this.resourceProperties.isAddMappings()) {logger.debug("Default resource handling disabled");} else {Duration cachePeriod = this.resourceProperties.getCache().getPeriod();CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();if (!registry.hasMappingForPattern("/webjars/**")) { //所有 /webjars/**this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));}String staticPathPattern = this.mvcProperties.getStaticPathPattern();if (!registry.hasMappingForPattern(staticPathPattern)) {this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));}}}
所有 /webjars/** 都去 classpath:/META-INF/resources/webjars/ 这里找资源
webjars: 以jar包方式引入静态资源
参考:https://www.webjars.org/
<!‐‐引入jquery‐webjar‐‐>在访问的时候只需要写webjars下面资源的名称即可 <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
引入后:
根据图生成地址
访问地址:http://localhost:8080/webjars/jquery/dist/jquery.js
在访问时候 只需要写webjars下面的资源名称即可
资源映射:
@ConfigurationProperties(prefix = "spring.resources",ignoreUnknownFields = false ) public class ResourceProperties {private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
可以设置和静态资源有关的参数, 缓存时间等
2)"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
classpath 等价于 Java包同级的目录
"classpath:/META‐INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" "/":当前项目的根路径
classpath:
比如:localhost:8080/abc === 去静态资源文件夹里面找abc
3)、欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射;
localhost:8080/ 找index页面
4)、所有的 **/favicon.ico 都是在静态资源文件下找;
其实都是可以配置的啊哈:
@ConfigurationProperties(prefix = "spring.resources",ignoreUnknownFields = false ) public class ResourceProperties {private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};private String[] staticLocations;private boolean addMappings;private final ResourceProperties.Chain chain;private final ResourceProperties.Cache cache;
可以修改静态文件夹位置!
Spring boot 不支持jsp ,Spring boot推荐使用模板引擎。
Velocty FreeaKer
模板:
把数据和模板 交给模板引擎
Spring boot 推荐使用 Thymeleaf
引入thymeleaf ,开发
引入相应的starter
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring‐boot‐starter‐thymeleaf</artifactId> 2.1.6 </dependency> 切换thymeleaf版本 <properties> <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version> <!‐‐ 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 ‐‐> <!‐‐ thymeleaf2 layout1‐‐> <thymeleaf‐layout‐dialect.version>2.2.2</thymeleaf‐layout‐dialect.version> </properties>
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的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2、使用thymeleaf语法;
<!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="${hello}">这是显示欢迎信息</div> </body> </html>
语法规则 自行学习吧 不详细介绍了
Spring Boot 与 Spring mvc 自动配置原理:
参考:https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications
1. Spring MVC auto-configuration
Spring Boot 自动配置好了SpringMVC
以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration):
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans,自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?))
到这个类里面去:
@Configuration @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 = "";private static final String[] SERVLET_LOCATIONS = { "/" };@Bean@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled",matchIfMissing = true)public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {return new OrderedHiddenHttpMethodFilter();}@Bean@ConditionalOnMissingBean(FormContentFilter.class)@ConditionalOnProperty(prefix = "spring.mvc.formcontent.filter", name = "enabled",matchIfMissing = true)public OrderedFormContentFilter formContentFilter() {return new OrderedFormContentFilter();}
这个类里面有这个配置:视图解析器 (我们可以给容器中添加视图解析器)
@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 uses all the other view resolvers to locate// a view so it should have a high precedence resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);return resolver;}
小结:
ContentNegotiatingViewResolver:组合所有的视图解析器的;
如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来;
(验证方法 在doDispatch方法 打断点 进来的是自己定义的视图解析器组件)
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;
关于Spring mvc的扩展问题,大家可以了解下。
<mvc:view‐controller path="/hello" view‐name="success"/><mvc:interceptors><mvc:interceptor><mvc:mapping path="/hello"/><bean></bean></mvc:interceptor></mvc:interceptors>
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc;
既保留了所有的自动配置,也能用我们扩展的配置;
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能 @Configuration public class MyMvcConfig extends WebMvcConfigurerAdapter {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {// super.addViewControllers(registry);//浏览器发送 /atguigu 请求来到 successregistry.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 {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {// super.addViewControllers(registry);//浏览器发送 /atguigu 请求来到 successregistry.addViewController("/atguigu").setViewName("success");} }
原理:
为什么@EnableWebMvc自动配置就失效了;
@EnableWebMvc的核心
@Import(DelegatingWebMvcConfiguration.class) public @interface EnableWebMvc {
@Configuration public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
@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最基本的功能;
总结:
如何修改SpringBoot的默认配置
模式:
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如
果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默
认的组合起来;
2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置
转载于:https://www.cnblogs.com/toov5/p/10747835.html
SpringBoot与web开发相关推荐
- SpringBoot的Web开发入门案例1
SpringBoot的Web开发入门案例1-登录和页面数据遍历读取 新建maven项目:logintest pom.xml文件: <project xmlns="http://mave ...
- SpringBoot的Web开发入门案例2—国际化
SpringBoot的Web开发入门案例2-国际化 改造logintest项目:SpringBoot的Web开发入门案例1 地址:https://blog.csdn.net/BLU_111/artic ...
- SpringBoot的Web开发入门案例9—数据访问
SpringBoot的Web开发入门案例9-数据访问 创建一个springboot项目(打包方式为jar包): 勾选Spring Web选项,勾选JDBC API和MySQL Driver pom文件 ...
- SpringBoot的Web开发入门案例7—WebMvcConfigurer配置类
SpringBoot的Web开发入门案例7-WebMvcConfigurer配置类 WebMvcConfigurer接口的几个常用方法: addViewControllers:配置请求路径和页面的映射 ...
- SpringBoot的Web开发入门案例3—异常处理
SpringBoot的Web开发入门案例3-异常处理 SpringBoot 默认404界面(由org.springframework.boot.autoconfigure.web.ErrorMvcAu ...
- SpringBoot的Web开发入门案例6—替换默认容器Tomcat
SpringBoot的Web开发入门案例6-替换默认容器Tomcat为Jetty Spring Boot默认是使用Tomcat作为内嵌的Servlet容器的,如需修改为Jetty,只要修改pom文件即 ...
- SpringBoot的Web开发入门案例5—注册Servlets, Filter, Listener
SpringBoot的Web开发入门案例5-注册Servlets, Filter, Listener 注册Servlet 创建MyServlet类 package com.blu.conf;impor ...
- SpringBoot的Web开发支持【超详细【一篇搞定】果断收藏系列】
SpringBoot的Web开发支持 常用的服务器配置 使用Jetty服务器替换Tomcat 排除Tomcat的启动器,引入Jetty application.yml 编写入口程序 编写Control ...
- Springboot的web开发-静态资源
1.web开发简介 SpringMVC自动配置概览 Spring Boot provides auto-configuration for Spring MVC that works well wit ...
- SpringBoot 之 Web开发
2.Web开发 2.1.SpringMVC自动化配置概述 Spring Boot provides auto-configuration for Spring MVC that works well ...
最新文章
- php 文字换行,用Php中的Fpdf换行文本
- springboot集成kafka及kafka web UI的使用
- 基于xml的方式配置AOP
- 【期望】【高斯消元】图上游走(金牌导航 期望-6)
- 安卓模拟器安装过程记录 20200926
- 多用户文件系统java实现_为什么要有文件系统?文件系统都有那些种类?
- form表单提交回调函数
- Python3.0 我的DailyReport 脚本(四)发送日报
- Windows的资源监视器
- 【暴强】200种好口碑便宜护肤品 - 生活至上,美容至尚!
- Excel把一个工作表根据条件拆分成多个工作表
- OL实现属性查询的功能
- LVDS、FPD-Link/GMSL、MIPI的区别
- php中常用的输出语句及其区别
- 如何获取京东推广的APPKEY
- [DB][Oracle]Oracle格式化数字的方法(指定小数点位数,每3位加逗号)
- Jquery的简单使用
- 掘金万亿母婴市场,宝宝树价值在哪里? | 一点财经
- html flash音乐播放器代码,网页上播放mp3或flash等播放器代码
- Postgresql杂谈 22——Postgresql中的模糊匹配
热门文章
- SpringMVC实现list表单(六)
- 电子相册系统(九)分页
- JSP的自定义标签(五)之Tag File
- 【渝粤教育】国家开放大学2018年春季 8662-22T特色课(1) 参考试题
- 【渝粤题库】陕西师范大学300013 西方史学史
- 机器学习调参-模型选择
- python2项目出现的错误(UnicodeDecodeError)
- 正则表达式,以python为例
- CF960G Bandit Blues 分治+NTT(第一类斯特林数)
- BZOJ 1717: [Usaco2006 Dec]Milk Patterns 产奶的模式( 二分答案 + 后缀数组 )