SpringBoot Web开发
创建SpringBoot应用,选中我们需要的模块SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来自己编写业务代码web自动配置规则
WebMvcAutoConfiguration WebMvcPropertiesViewResolver自动配置静态资源自动映射Formatter与Converter自动配置HttpMessageConverter自动配置静态首页favicon 错误处理 SpringBoot对静态资源的映射规则 WebMvcAutoConfiguration类的addResourceHandlers方法:(添加资源映射) 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/**")) { 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)); } } }所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源 webjars:以jar包的方式引入静态资源; webjars官网 添加好依赖: 在以来的jar包里找到 然后我们在前台访问这个文件,访问到了。。。。开心 http://localhost:8080/webjars/jquery/3.5.1/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/"}; private String[] staticLocations; private boolean addMappings; private final ResourceProperties.Chain chain; private final ResourceProperties.Cache cache; public ResourceProperties() { this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS; this.addMappings = true; this.chain = new ResourceProperties.Chain(); this.cache = new ResourceProperties.Cache(); }上图中添加的映射访问路径staticPathPattern值是/**,对应的资源文件夹就是上面配置类ResourceProperties中的CLASSPATH_RESOURCE_LOCATIONS数组中的文件夹: 首先我们先知道CLASSPATH指的是哪里,就是下图中的java,resources. 我们放到第一个位置/Meta-info/resources/下,然后去访问(如下边两张图)。(其他的位置不一一试了。) 欢迎页映射 location就是静态资源路径,所以欢迎页的页面就是上面静态资源下的index.html,被/**映射,因此直接访问项目就是访问欢迎页 做一做:
放在我们上边的四个路径下的任意一个路径即可,名称为index.html 网站图标映射(favicon.ico) 所有的 favicon.ico 都是在静态资源文件下找(就是上边的那四个路径的其中一个路径。) 我们还可以通过配置文件,自己指定静态资源文件夹 缺点: 系统帮我们指定的静态文件夹就访问不到了,只能访问到你自己设置的这个文件夹。
