說在前面的話:css
因爲 Spring Boot 採用了」約定優於配置」這種規範,因此在使用靜態資源的時候也很簡單。
SpringBoot本質上是爲微服務而生的,以JAR的形式啓動運行,可是有時候靜態資源的訪問是必不可少的,好比:image、js、css 等資源的訪問html
簡單瞭解便可,感受實用性不大,java
public class WebMvcAutoConfiguration { 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(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } } }
代碼分析: 全部 /webjars/**
,都去 classpath:/META-INF/resources/webjars/
找資源;webjars:以jar包的方式引入靜態資源; webjars提供的依賴官網jquery
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>1.12.4</version> </dependency>
啓動服務,測試訪問靜態地址http://127.0.0.1:8001/hp/webjars/jquery/1.12.4/jquery.js
web
@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(); } public String[] getStaticLocations() { return this.staticLocations; } }
摘抄了部分源碼,算是爲了增長篇幅,從上述代碼中咱們能夠看到,提供了幾種默認的配置方式spring
classpath:/static classpath:/public classpath:/resources classpath:/META-INF/resources 備註說明: "/"=>當前項目的根路徑
咱們在src/main/resources目錄下新建 public、resources、static 、META-INF等目錄目錄,並分別放入 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg 五張圖片。跨域
注意:須要排除webjars的形式,將pom.xml中的代碼去掉,在進行測試結果結果以下springboot
咱們在spring.resources.static-locations
後面追加一個配置classpath:/os/
:mvc
# 靜態文件請求匹配方式 spring.mvc.static-path-pattern=/** # 修改默認的靜態尋址資源目錄 多個使用逗號分隔 spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/os/
在實際開發中,咱們可能須要自定義靜態資源訪問以及上傳路徑,特別是文件上傳,不可能上傳的運行的JAR服務中,那麼能夠經過繼承WebMvcConfigurerAdapter來實現自定義路徑映射。app
application.properties 文件配置:
# 圖片音頻上傳路徑配置(win系統自行變動本地路徑) web.upload.path=D:/upload/attr/
Demo05BootApplication.java 啓動配置:
package com.hanpang; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootApplication public class Demo05BootApplication implements WebMvcConfigurer { private final static Logger LOGGER = LoggerFactory.getLogger(Demo05BootApplication.class); @Value("${web.upload.path}") private String uploadPath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/uploads/**").addResourceLocations( "file:" + uploadPath); LOGGER.info("自定義靜態資源目錄、此處功能用於文件映射"); } public static void main(String[] args) { SpringApplication.run(Demo05BootApplication.class, args); } }
依然從源碼出手來解決這個問題
public class WebMvcAutoConfiguration { private Optional<Resource> getWelcomePage() { String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations()); return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst(); } private Resource getIndexHtml(String location) { return this.resourceLoader.getResource(location + "index.html"); } }
歡迎頁; 靜態資源文件夾下的全部index.html頁面,被"/**"映射;
新增模版引擎的支持
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
配置核心文件application.properties
server.port=8001 server.servlet.context-path=/hp spring.mvc.view.prefix=classpath:/templates/
沒有去設置後綴名
設置增長路由
@Controller public class IndexController { @GetMapping({"/","/index"}) public String index(){ return "default"; } }
http://127.0.0.1:8001/hp/
新增模版引擎的支持
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
配置核心文件application.properties
server.port=8001 server.servlet.context-path=/hp spring.mvc.view.prefix=classpath:/templates/
沒有去設置後綴名
啓動文件的修改以下
@SpringBootApplication public class Demo05BootApplication implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("default"); registry.addViewController("/index1").setViewName("default"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); } public static void main(String[] args) { SpringApplication.run(Demo05BootApplication.class, args); } }
@Configuration @ConditionalOnProperty( value = {"spring.mvc.favicon.enabled"}, matchIfMissing = true ) public static class FaviconConfiguration implements ResourceLoaderAware { private final ResourceProperties resourceProperties; private ResourceLoader resourceLoader; public FaviconConfiguration(ResourceProperties resourceProperties) { this.resourceProperties = resourceProperties; } public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(-2147483647); mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler())); return mapping; } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); requestHandler.setLocations(this.resolveFaviconLocations()); return requestHandler; } private List<Resource> resolveFaviconLocations() { String[] staticLocations = WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.getResourceLocations(this.resourceProperties.getStaticLocations()); List<Resource> locations = new ArrayList(staticLocations.length + 1); Stream var10000 = Arrays.stream(staticLocations); ResourceLoader var10001 = this.resourceLoader; var10001.getClass(); var10000.map(var10001::getResource).forEach(locations::add); locations.add(new ClassPathResource("/")); return Collections.unmodifiableList(locations); } }
SpringBoot 默認是開啓Favicon,而且提供了一個默認的Favicon,若是想關閉Favicon,只須要在application.properties中添加
spring.mvc.favicon.enabled=false
若是想更改Favicon,只須要將本身的Favicon.ico(文件名不能改動),放置到類路徑根目錄、類路徑META_INF/resources/下、類路徑resources/下、類路徑static/下或者類路徑public/下。
在Springboot中配置WebMvcConfigurerAdapter的時候發現這個類過期了。因此看了下源碼,發現官方在spring5棄用了WebMvcConfigurerAdapter,由於springboot2.0使用的spring5,因此會出現過期。
WebMvcConfigurerAdapter已通過時,在新版本中被廢棄,如下是比較經常使用的重寫接口:
/** 解決跨域問題 **/ public void addCorsMappings(CorsRegistry registry) ; /** 添加攔截器 **/ void addInterceptors(InterceptorRegistry registry); /** 這裏配置視圖解析器 **/ void configureViewResolvers(ViewResolverRegistry registry); /** 配置內容裁決的一些選項 **/ void configureContentNegotiation(ContentNegotiationConfigurer configurer); /** 視圖跳轉控制器 **/ void addViewControllers(ViewControllerRegistry registry); /** 靜態資源處理 **/ void addResourceHandlers(ResourceHandlerRegistry registry); /** 默認靜態資源處理器 **/ void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
@Configuration public class WebMvcConfg implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index").setViewName("index"); } }
@Configuration public class WebMvcConfg extends WebMvcConfigurationSupport { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index").setViewName("index"); } }
其實,源碼下WebMvcConfigurerAdapter是實現WebMvcConfigurer接口,因此直接實現WebMvcConfigurer接口也能夠;WebMvcConfigurationSupport與WebMvcConfigurerAdapter、接口WebMvcConfigurer處於同一個目錄下WebMvcConfigurationSupport包含WebMvcConfigurer裏面的方法,由此看來版本中應該是推薦使用WebMvcConfigurationSupport類的,WebMvcConfigurationSupport應該是新版本中對WebMvcConfigurerAdapter的替換和擴展
// 能夠直接使用addResourceLocations 指定磁盤絕對路徑,一樣能夠配置多個位置,注意路徑寫法須要加上file: registry.addResourceHandler("/myimgs/**").addResourceLocations("file:H:/myimgs/");
// 訪問myres根目錄下的fengjing.jpg 的URL爲 http://localhost:8080/fengjing.jpg (/** 會覆蓋系統默認的配置) registry.addResourceHandler("/**").addResourceLocations("classpath:/myres/").addResourceLocations("classpath:/static/");