1.web开发简介

SpringMVC自动配置概览

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.(大多场景我们都无需自定义配置)
Springboot给springMVC配置了以下场景:
The auto-configuration adds the following features on top of Spring’s defaults:

Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
      内容协商视图解析器和BeanName视图解析器

Support for serving static resources, including support for WebJars (covered later in this document)).
      静态资源(包括webjars)

Automatic registration of Converter, GenericConverter, and Formatter beans.
      自动注册 Converter,GenericConverter,Formatter

Support for HttpMessageConverters (covered later in this document).
      支持 HttpMessageConverters (后来我们配合内容协商理解原理)

Automatic registration of MessageCodesResolver (covered later in this document).
      自动注册 MessageCodesResolver (国际化用)

Static index.html support.
      静态index.html 页支持

Custom Favicon support (covered later in this document).
      自定义 Favicon

Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
      自动使用 ConfigurableWebBindingInitializer ,(DataBinder负责将请求数据绑定到JavaBean上)

新建web项目




web场景-静态资源规则与定制化

静态资源目录

只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources
我们验证一下静态资源放在上述几个目录下能否正常访问。

测试结果

访问 : 当前项目根路径/ + 静态资源名,例如http://localhost:8080/bytedance.png
原理: 静态映射/ **。
请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面

比如下面我们在Controller中也有一个mayi.png的请求

@RestController
public class HelloController {@RequestMapping("/mayi.png")public String hello(){return "aaaa";}
}


也可以改变默认的静态资源路径,/static,/public,/resources, /META-INF/resources失效

resources:static-locations: [classpath:/haha/]

以后只能在类路径下的haha文件夹中找到静态资源。
想写更多的路径,可以在后面加逗号
按照原来的方式访问。

静态资源访问前缀

静态资源默认是项目根路径+静态资源名就能访问。比如我们写了web程序,里面有很多静态资源也有很多动态请求,我们现在有登录拦截器,只有登录以后才能访问动态请求,如果我们拦截/**,就把很多静态资源给拦截了,为了让静态资源访问方便,我们给静态资源加上前缀,这样我们可以让拦截器放行指定路径的所有请求。

默认无前缀
在application.yml中加上如下内容

spring:mvc:static-path-pattern: /res/**

当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找
比如下面的例子就是http://localhost:8080/res/baidu.png

webjar

可用jar方式添加css,js等资源文件,

https://www.webjars.org/

例如,添加jquery

<dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>3.5.1</version>
</dependency>

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径。

web场景-welcome与favicon功能

官方文档

欢迎页支持

springboot支持两种方式欢迎页,第一种静态方式,我们将index.html放入到静态资源目录下,它就会被当成欢迎页,即访问我们项目根路径得到的页面。还有模板方式,也就是静态资源目录下没有这样的页面,也可以给我们找。比如说写了controller处理index请求。
1.静态资源路径下 index.html
可以配置静态资源路径
但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问

spring:
#  mvc:
#    static-path-pattern: /res/**   这个会导致welcome page功能失效resources:static-locations: [classpath:/haha/]

2.controller能处理/index

自定义Favicon

指网页标签上的小图标。

favicon.ico 放在静态资源目录下即可。

spring:
#  mvc:
#    static-path-pattern: /res/**   这个会导致 Favicon 功能失效

静态资源配置管理

简介

SpringBoot启动默认加载 xxxAutoConfiguration 类(自动配置类)
SpringMVC功能的自动配置类WebMvcAutoConfiguration,生效

@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 {...
}

WebMvcConfigurationSupport注意容器中没有这个组件的时候,下面才生效。这就表明springboot要全面接管springmvc

给容器中配置的内容:
    配置文件的相关属性的绑定:WebMvcPropertiesspring.mvc、ResourcePropertiesspring.resources

@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {...
}

配置类只有一个有参构造器

配置类只有一个有参构造器。有参构造器所有参数的值都会从容器中确定

public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider, ObjectProvider<WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider, ObjectProvider<DispatcherServletPath> dispatcherServletPath, ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {this.resourceProperties = resourceProperties;this.mvcProperties = mvcProperties;this.beanFactory = beanFactory;this.messageConvertersProvider = messageConvertersProvider;this.resourceHandlerRegistrationCustomizer = (WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer)resourceHandlerRegistrationCustomizerProvider.getIfAvailable();this.dispatcherServletPath = dispatcherServletPath;this.servletRegistrations = servletRegistrations;}

ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
ListableBeanFactory beanFactory Spring的beanFactory,容器工厂,即IOC
HttpMessageConverters 找到所有的HttpMessageConverters
ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。
DispatcherServletPathDispatcherServlet能处理的路径
ServletRegistrationBean 给应用注册Servlet、Filter…

资源处理的默认规则

...
public class WebMvcAutoConfiguration {...public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {...@Overridepublic 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();//注册第一种规则,webjars的规则if (!registry.hasMappingForPattern("/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(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));}}}...}...
}

注意:add-mappings设置false,表示禁用静态资源的路径映射,所有静态资源都将失效。

根据上述代码,通过配置 add-mappings为falsem,我们可以同过配置禁止所有静态资源规则

spring:resources:add-mappings: false   #禁用所有静态资源规则

静态资源规则:

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/" };/*** Locations of static resources. Defaults to classpath:[/META-INF/resources/,* /resources/, /static/, /public/].*/private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;...
}

这就解释了为什么静态资源的默认的4个位置。

欢迎页的处理规则

HandlerMapping处理器映射, 保存了每一个handler器处理哪些规则。

...
public class WebMvcAutoConfiguration {...public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {...@Beanpublic WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),this.mvcProperties.getStaticPathPattern());welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());return welcomePageHandlerMapping;}

WelcomePageHandlerMapping的构造方法如下:

WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,ApplicationContext applicationContext, Resource welcomePage, String staticPathPattern) {if (welcomePage != null && "/**".equals(staticPathPattern)) {//要用欢迎页功能,必须是/**logger.info("Adding welcome page: " + welcomePage);setRootViewName("forward:index.html");}else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {//调用Controller /indexlogger.info("Adding welcome page template: index");setRootViewName("index");}
}

这构造方法内的代码也解释了web场景-welcome与favicon功能中配置static-path-pattern了,welcome页面和小图标失效的问题。

Springboot的web开发-静态资源相关推荐

  1. Web开发静态资源处理---SpringBoot

    Web开发静态资源处理 使用SpringBoot的步骤: 1.创建一个SpringBoot应用,选择我们需要的模块,SpringBoot就会默认将我们的需要的模块自动配置好 2.手动在配置文件中配置部 ...

  2. springboot10 Web开发静态资源

    10.Web开发静态资源处理 接下来呢,开始学习SpringBoot与Web开发,其实SpringBoot的东西用起来非常简单,因为SpringBoot最大的特点就是自动装配. 使用SpringBoo ...

  3. SpringBoot的Web开发入门案例7—WebMvcConfigurer配置类

    SpringBoot的Web开发入门案例7-WebMvcConfigurer配置类 WebMvcConfigurer接口的几个常用方法: addViewControllers:配置请求路径和页面的映射 ...

  4. SpringBoot的Web开发支持【超详细【一篇搞定】果断收藏系列】

    SpringBoot的Web开发支持 常用的服务器配置 使用Jetty服务器替换Tomcat 排除Tomcat的启动器,引入Jetty application.yml 编写入口程序 编写Control ...

  5. Spring-Boot:写出来的网站访问不到静态资源?怎样通过url访问SpringBoot项目中的静态资源?localhost:8989/favicon.ico访问不了工程中的图标资源?

    Spring-Boot:Spring-Boot写出来的网站访问不到静态资源?怎样通过url访问SpringBoot项目中的静态资源?localhost:8989/favicon.ico访问不了工程中的 ...

  6. SpringBoot直接URL获取静态资源文件

    SpringBoot直接URL获取静态资源文件 spring boot 直接通过url访问获取内部或者外部静态资源图片 https://blog.csdn.net/ljj_9/article/deta ...

  7. SpringBoot的Web开发入门案例2—国际化

    SpringBoot的Web开发入门案例2-国际化 改造logintest项目:SpringBoot的Web开发入门案例1 地址:https://blog.csdn.net/BLU_111/artic ...

  8. 2012年度最新免费web开发设计资源荟萃

    为什么80%的码农都做不了架构师?>>>    日期:2012-9-11  来源:GBin1.com 免费的设计和开发资源大家肯定都喜欢,在这篇文章中我们收集了7月到8月的最新免费开 ...

  9. SpringBoot的Web开发入门案例1

    SpringBoot的Web开发入门案例1-登录和页面数据遍历读取 新建maven项目:logintest pom.xml文件: <project xmlns="http://mave ...

最新文章

  1. 获得诺贝尔奖的底层小职员 | 从来没有一个高手,是在一夜之间强大起来的
  2. 设置网络映射后,电脑重启后自动重连
  3. partial in latex
  4. java 验证码 插件_javaweb中验证码插件Kaptcha的使用
  5. [BZOJ3000] Big Number (Stirling公式)
  6. 华为Mate 40E预约页面突然上线:或搭载麒麟990E芯片
  7. jq和thinkphp经常使用的几种ajax
  8. xamarin.android listview绑定数据及点击事件
  9. 嵌入式Linux系统工程师系列之ARM920T的MMU与Cache
  10. 【产品功能】弹性网卡支持私网多IP
  11. 财务金额转换:小写金额转换成大写算法
  12. eoj 3279 爱狗狗的两个dalao(dfs)
  13. 初二年级男生厌学家长应该怎么应对
  14. uni-app 父传子、子传父、路径传参、本地存储
  15. 词嵌入向量WordEmbedding的原理和生成方法
  16. 有关statistics
  17. 拆机详解2:比Macintosh还早?苹果Lisa拆解
  18. 米卢:梅西是世界最佳 弗格森没有犯错误
  19. 常见的嵌入式微处理器(Micro Processor Unit,MPU)
  20. cad中简单流程图制作_1600字解读装修施工流程,看完你就入门了!(流程图制作中)...

热门文章

  1. 基于Linux和MiniGUI的嵌入式系统软件开发指南(七)
  2. 设计模式 - 访问者模式
  3. android unity 关闭应用_使用Android Studio在安卓平台Profile Unity应用
  4. python tkinter库四则运算_python tkinter 编写心理学试验程序干扰任务之四则运算 psychopy...
  5. python成绩统计_python统计考试成绩排名
  6. linux netlink 内核配置,如何在linux内核模块中加入netlink通信接口
  7. ashx文件 验证是否登录_汇总丨增值税综合服务平台登录常见问题解答
  8. 【flink】Flink 1.12.2 源码浅析 : StreamTask 浅析
  9. 【Flink】Flink 的 slotSharingGroup 有什么用
  10. 【Elasticsearch】 Elasticsearch并发冲突问题